I have a page that uses the jQuery UI datepicker. I'm trying to make the following happen on my page:
click on the date field -> calendar pops up (datepicker takes care of this)
click on a calendar day -> ajax request fires off, does some server-side calculations (checking for scheduling conflicts and the like), and displays a warning if it's a busy day
It's not exactly a validation, as the intent is to display a warning but still allow the user to submit whatever day they want.
What I have so far fires off the ajax, but with the wrong date. I think it's grabbing the date at page-load rather than when a calendar-day is clicked, so I'm guessing datepicker('getDate') is being evaluated at load time. How can I construct this to evaluate dynamically? Here's the current version (in coffeescript):
jQuery ->
$("#rescheduler").click ->
$("td[data-handler='selectDay'] a").click ->
id = getUrlVars()["booking_id"]
newDate = new Date(datepicker.datepicker('getDate'))
postData = {}
postData['booking_id'] = id
postData['date'] = newDate
$.post '/path/to/check_stuff', postData, ((data) -> doStuff), "json"
or, if you prefer native javaScript:
jQuery(function() {
return $("#rescheduler").click(function() {
return $("td[data-handler='selectDay'] a").click(function() {
var id, newDate, postData;
id = getUrlVars()["booking_id"];
newDate = new Date(datepicker.datepicker('getDate'));
postData = {};
postData['booking_id'] = id;
postData['date'] = newDate;
return $.post('/path/to/check_stuff', postData, (function(data) {
return doStuff;
}), "json");
});
});
});
I suspect that what is happening is the date picker sets the date as, say, March 2, 2014 but this is set as UTC time so the value is something like March 2, 2014 00:00:00. Then when you create the new date from the passed in values your timezone gets added to the mix, causing the date to appear to be off.
If this is so (try logging some of the values to see what, exactly, you are working with) then you need to modifying the date picker value to account for time zone.
Something like:
localDate = new Date(dateToFix); //dateToFix would be the value from the date picker
localTime = localDate.getTime();
localOffset = localDate.getTimezoneOffset() * 60000;
adjustedDate = new Date(localTime + localOffset);
Related
I need to save the view's state when page is reloaded. In other words, when users refresh the page, they should go back to the month they were before.
I am currently using "datesSet" callback in order to store the current date in localStorage, like this :
datesSet: function( dateInfo)
{
localStorage.fullCalendarDefaultDate = dateInfo.startStr;
}
And when i initialize fullCalendar, i use the "initialDate" parameter to set the default date :
initialDate: localStorage.fullCalendarDefaultDate
The problem is, this is not working in month view. As the "starting day" is not necessarily in the current month (ex below), the month view won't initialize on the correct month when page reloads...
Here, the "starting day" would be March 26th, and FC will init on march on next reload...
Thanks ADyson for the solution :
datesSet: function( dateInfo)
{
var date = new Date(dateInfo.view.currentStart);
localStorage.fullCalendarDefaultDate = date.toISOString();
}
I want to use pure javascript datetime picker in Tabulator.js. Usually I use Materializecss but they don`t provide datetime picker. Only date or time. So I had to find one. I chose rome although I liked better dtsel - it got much nicer time picker but I have not found cdn for it.
I found that Tabulator provides a way to implement customer editors. In my code (see jsFiddle) it is the editor:dateEditorOriginal function. It works nicely and even provides build in calendar. Could someone tell where the calendar comes from? Tabulator or moment?
But I need datetime so please have have a look at the var dateEditor. I tried to use rome picker but I am not able to make it work. I am able to select the date and time but it will not pass it to Tabulator.
var dateEditor = function(cell, onRendered, success, cancel, editorParams){
//cell - the cell component for the editable cell
//onRendered - function to call when the editor has been rendered
//success - function to call to pass the successfuly updated value to Tabulator
//cancel - function to call to abort the edit and return to a normal cell
//editorParams - params object passed into the editorParams column definition property
//create and style editor
var editor = document.createElement("input");
//var cellValue = cell.getValue()
var cellValue = moment(cell.getValue(), "DD-MM-YYYY HH:mm").format("DD-MM-YYYY HH:mm")
// editor.setAttribute("type", "date");
var cal
//create and style input
editor.style.padding = "3px";
editor.style.width = "100%";
editor.style.boxSizing = "border-box";
//Set value of editor to the current value of the cell
// editor.value = moment(cell.getValue(), "YYYY-MM-DD HH:mm").format("YYYY-MM-DD HH:mm")
//editor.value = cellValue
//set focus on the select box when the editor is selected (timeout allows for editor to be added to DOM)
onRendered(function(){
//console.log(cellValue)
cal = rome(editor,{
"inputFormat": "DD-MM-YYYY HH:mm",
"initialValue": cellValue,
"timeInterval": 600,
"weekStart": 1
})
// editor.focus();
// editor.style.css = "100%";
});
//when the value has been set, trigger the cell to update
function successFunc(){
var tmp = editor.value
console.log(cal.getDate())
console.log(tmp)
console.log(cell.getValue())
// success(tmp)
// success(moment(editor.value, "DD-MM-YYYY HH:mm").format("DD-MM-YYYY HH:mm"));
}
editor.addEventListener("change", successFunc);
editor.addEventListener("blur", successFunc);
//return the editor element
return editor;
};
Could someone help me to implement pure javascript datetime picker in Tabulator?
Here is jsFiddle. The column From uses my implementation of datetime picker and column To uses original dateEditor.
The issue I am facing to is that with the current set up the correct date is selected, passed to the input field but not to the Tabulator. It is my explanation what is happening if I am correct. Once the date & time selection finished I want it to see it in the Tabulator.
If you don't have to use Rome, I can suggest using flatpickr instead.
var dateEditor = (cell, onRendered, success, cancel, editorParams) => {
var editor = document.createElement("input");
editor.value = cell.getValue();
var datepicker = flatpickr(editor, {
enableTime: true,
dateFormat: "j-n-Y H:i",
onClose: (selectedDates, dateStr, instance) => {
success(dateStr);
instance.destroy();
},
});
onRendered(() => {
editor.focus();
});
return editor;
};
Here is an example:
https://jsfiddle.net/fazLh6v0/
you must call success() to update Tabulator.
for some reason (that I spent WAY too much time on but didnt get an answer), success() in your example does NOT like to be called with the existing cell value ?
So I added :
(cell.getValue() != cal.getDateString()) && success(cal.getDateString());
It also didnt like that your 2nd row doesnt have a timecode in it, so the first choice of using the time selector is ignored, and sets it to 00:00, then the 2nd (and further applications) go as expected.
Solving these other problems, is up to you I guess, coz I dont use rome.
I just use the builtin <input type=datetime-local>
Your Problem is that the blur event (You use it to capture the finish of the user) triggers already when the user clicks on the calendar - so before his choice is processed.
The only solution I could find is to use another framework.
With flatpickr (It also has a time feature and looks much nicer) for example, you can define a close event that triggers the success function.
(just like Tim's solution)
Here's our scenario:
We are using node w/ express for our web app and we need to create a background process that continuously checks the created date on multiple posts and when they expire. These expired dates are set by the user so the posts expire at different rates. When the date expires, our app should be triggering specific events.
We are considering using a "setInterval" but wasn't sure if this is the best long-term solution.
Is there a solution to have node continuously check whether or not a date has been expired? Upon expiring, the posts must trigger specific functions.
There are two ways to do this:
1) use moment lib like this:
var date = moment("2013-03-24")
var now = moment();
if (now > date) {
// date is past
} else {
// date is future
}
2) use node-schedule like this:
var schedule = require('node-schedule');
var futureDate = new Date(new Date().getTime() + 60 * 60 * 24 * 1000); // This is 24 hours from *now*
var j = schedule.scheduleJob(futureDate, function(){
console.log('Do your work here.');
});
Im not sure about your code but if u can catch the event when the users post, the easy way would be
setTimeout(whateverYouHaveTodo, expireTimeInMilliseconds);
each time an event is triggered.
And if you need to cancel the timeouts in the future, what i do personally is put the timeouts in a json object with the key as a unique id which you could identify the event specifically
I am using glDatePicker plugin.
To change dynamically selected date I call following code where dateDepartureVar is the constructor of glDatePicker object.
dateDepartureVar.options.selectedDate = new Date(2015, 9, 18);
dateDepartureVar.render();
This code changes the selectedDate however when the calendar is opened again, it does not open on the selectedDate, it opens wherever it was left off before.
I need the calendar to open exactly on selectedDate. What am I missing?
Please verify you have correctly obtained an instance of the datepicker when you initialized. here's an excerpt (slightly edited) from the official documentation :
When attaching your input, you can pass true to the second call to the glDatePicker constructor to get an instance of glDatePicker returned. You can also do this while chaining with options:
// Doing it in a single pass
var dateDepartureVar = $('#example1').glDatePicker(
{
showAlways: true,
selectableDOW: [0, 2, 3]
}).glDatePicker(true); //Pass true here
More info here (official docs)
This worked for me.
The trick is set firstDate too.
$('select[name="monthSelect"]').change(function() {
let newDate = new Date((new Date()).getFullYear(), parseInt($(this).val())-1, 1);
$.extend(calendar.options, {
selectedDate: newDate,
firstDate: newDate
});
calendar.render();
});
I was creating a countdown timer using javascript; I can use jQuery. I want the global time not the PC time.
How could I get the global time using javascript or the jQuery?
Use a time API like: http://www.timeapi.org/
<script type="text/javascript">
function myCallback(json) {
alert(new Date(json.dateString));
}
</script>
<script type="text/javascript" src="http://timeapi.org/utc/now.json?callback=myCallback"></script>
You can use the UTC methods from Date object: http://www.w3schools.com/jsref/jsref_obj_date.asp
var utcDate = new Date(json.dateString);
alert(utcDate.getUTCFullYear() + '-' + utcDate.getUTCMonth() + utcDAte.getUTCDate());
Well unless you make a request to some service that publishes like the current time of an atomic clock or something, you'll have to rely on your computers local time. As JS inherently relies on your local system.
The Date object has built-in methods for getting UTC values. Instead of myDate.getHours() use myDate.getUTCHours(), etc.
See the MDN reference for JavaScript date methods.
Using your current API with server time like following:
res.send(new Date());
You can get an approximate clock difference time with following:
// Get current local time before request
const initialLocalTime = new Date().getTime();
// Request server time
const response = await fetch('/api/time');
const data = await response.json();
const serverTime = new Date(data);
// Get current local time after request
const finalLocalTime = new Date().getTime();
// Calculate the request time
const dateDiff = finalLocalTime - initialLocalTime;
// Apply the request time to server time
serverTime.setTime(serverTime.getTime() + dateDiff);
// Calculate the time difference
const diff = serverTime.getTime() - finalLocalTime;
// Return the final difference time
return diff;
And, you can use the diff value in your page:
const now = new Date()
now.setTime(now.getTime() + diff);
console.info('Current time:', now);