I'm using datepicker in an input form, and sending the results through json to a database. I am using this line, to get the date from the datePicker:
date = $("#datepicker").datepicker('getDate');
Now, I would expect this to return 2014-04-03T00:00:00.000Z
But in fact it returns 2014-04-02T22:00:00.000Z
Notice the two hour difference, which unintentionally changes the day of month as well. I have no use for the hours and the smaller time units. However I do want the date to be right, without adding a dreaded +1 to my code. I suspect this has something to do with time zones, but I can't seem to find a solution to it in the documentation, or other Q&A's online. Could anyone point me in the right direction? My time zone is GMT +1 if that matters.
Thanks :)
I solved this a while ago, but forgot to post an answer.
After retrieving date, this is how i fixed it:
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
voilla
I could not figure out what you did there so I came up with a bit of a hackterrific solution.
I took the value of the alt field in UNIX:
$( function() {
$( "#datepicker" ).datepicker({
altField: "#alternate",
altFormat: "#",
});
It came out all sorts of weird with 3 extra 0's and a day behind my time zone.
So I figured out the difference and added it on.
var a = document.getElementById("alternate").value; // take alternative field UnixTimeStamp value
a = a.slice(0, -3); // get rid of 3 extra 0's
a = +a + +57000; // convert to Thai time
Related
I do let fullcalendar initialize normally. So it represents current date. (Midnight->midnight, 1day, 1h slots)
From some other datasource I get data with timestamps. The format is "YYYY-MM-DD HH:mm" (transmitted as a string, no timezone information)
So I convert that string to a moment object and test against fullcalendar.start and .end to see if it is within.
moment("2016-04-07 00:00") == $('#calendar').fullCalendar('getView').end
This results in false though the following command
$('#calendar').fullCalendar('getView').end.format("YYYY-MM-DD HH:mm")
returns
"2016-04-07 00:00"
I also tried to compare with diff
moment("2016-04-07 00:00").diff( $('#calendar').fullCalendar('getView').end,"minutes")
which returns
120
Some research on the calendars.end object in Chrome Dev Tools revealed that it internally is represented as
2016-04-07 02:00 GMT+0200
This looks strange to me. I am in timezone 2h ahead of GMT. So it should correctly say 2016-04-07 00:00 GMT+0200, should it not?
This also explains why the diff test above resulted in 120 minutes.
Can someone help? I do not get where the conversion problem comes from. I am using only dates with no timezone information. And as said above, fullcalendar initalizes with no gotodate information and shows a time bar from 00:00 to 00:00. So why does it come that there is this 2h difference?
Thanks a lot. I do understand things a lot better now.
Some of the dates I tried to compare were 'now'. I got 'now' by
var n = moment()
That turned out to be a date time including my timezone.
E.g. moment().format() resulted in '2016-04-07 00:00 GMT+0200' and I now see how this went wrong excepting a comparison against full calendar.end to be true but it was false as '2016-04-07 00:00 GMT+0200' is '2016-04-06 22:00' at UTC.
As
moment.utc()
does not work, I know ended up with using
moment.utc(moment().format('YYYY-MM-DD HH:mm'))
This now seems to work as this treats my local time as it would be the 'numerical same time' at UTC.. thus matching with how fullcalendar handles times internally (ambiguously-zones moments).
Thanks
A few things:
The timezone parameter controls how FullCalendar works with time zones.
By default, FullCalendar uses "ambiguously-zoned moments". These are customizations to moment.js made within fullCalendar. The docs state:
The moment object has also been extended to represent a date with no specified timezone. Under the hood, these moments are represented in UTC-mode.
Thus, to compare dates in this mode, treat them as if they were in UTC.
moment.utc("2016-04-07 00:00")
To compare moments, use the moment query functions, isSame, isBefore, isAfter, isSameOrBefore, isSameOrAfter, and isBetween.
In this case, since FullCalendar's start is inclusive but the end date is exclusive, you probably want to compare like this:
var cal = $('#calendar').fullCalendar('getView');
var start = cal.start;
var end = cal.end;
var m = moment.utc("2016-04-07 00:00"); // your input
var between = m.isSameOrAfter(start) && m.isBefore(end);
Note that there's an pending enhancement to moment's isBetween functionality for a future release that will give you control of exclusivity, but currently isBetween is fully inclusive, so you have to use the combination of functions shown here.
I realize dates can be very tricky in JavaScript, however I am encountering a somewhat strange issue.
Hopefully someone will be able to shed some light on it!
I am taking a date input from webshim datepicker and doing the following
var date = $scope.date;
console.log('date', date);
date.setTime(date.getTime() + date.getTimezoneOffset()*60*1000);
console.log('after set time', date);
Which will log something along the lines of
date "2025-06-19T00:00:00.000Z"
after set time "2025-06-19T12:00:00.000Z"
Notice the hours are different but it's still the same day (the 19th)
However, if I switch to another view and return to this input and log the input again (different date then the one above) I get something like
date "2025-10-22T12:00:00.000Z"
after set time "2025-10-23T00:00:00.000Z"
Again the hours have changed as expected but this time the day is one day off (the 23rd vs the 22nd)
If I change view once more and return again, the logged output will return to being the same day.
Basically this behavior is being switched every time I switch views. Is this very unusual or a typical problem? By views I am referring to Angular partials e.g.
<script>
View 1
</script>
<script>
View 2
</script>
Any thoughts or advice would be really great.
Finding the date of a specific day of the current week with Moment.js
There are lots of ways to manipulate dates in javascript. I've been looking for the simplest, easiest way to do so without long, ugly code, so someone showed me Moment.js.
I want to use the current date to discover the date of a specific day of the current week with this library. My attempt so far involves taking the difference between the current day number(days 0-6) and checking how many days are between it and monday(day 1), which is not right at all.
Here's my fiddle.
Here's my code:
var now = moment();
var day = now.day();
var week = [['sunday',0],['monday',1],['tuesday',2],['wednesday',3],['thursday',4],['friday',5],['saturday',6]];
var monday = moment().day(-(week[1][1] - day));//today minus the difference between monday and today
$("#console").text(monday);
//I need to know the date of the current week's monday
//I need to know the date of the current week's friday
How can I do this? My method may be a terrible way to get this done, or it might be somewhat close. I do, however want the solution to be neat, small, dynamic, and simple, as all code should be.
I'd prefer not to use native JS date functionality which produces ugly, messy code in every situation that I've seen.
this week's sunday
moment().startOf('week')
this week's monday
moment().startOf('isoweek')
this week's saturday
moment().endOf('week')
difference between the current day to sunday
moment().diff(moment().startOf('week'),'days')
this week's wedesday
moment().startOf('week').add('days', 3)
Maybe a little late to the party, but here's the proper way to do this, as in the documentation.
moment().day(1); // Monday in the current week
Also if in your locale it happens that the week starts with Monday and you wish to get a locally aware result, you can use moment().weekday(0). Here's the documentation for the moment().weekday(dayNumber) method.
It's not longer possible to use just a string (e. g. 'isoweek'), we need to use it like this:
import * as moment from 'moment';
import { unitOfTime } from 'moment';
moment().startOf('isoweek' as unitOfTime.StartOf);
I don't really know too much about core JavaScript, just a dot of jQuery. But I know jQuery is not necessary for what I need here:
I want to use the getdate function to find out the server's day of the week. Then add a bunch of clauses like:
if its Monday add 6 to the date and return the date in MM/DD/YYYY form.
if its Tuesday add 5 to the date and return the date in MM/DD/YYYY form.
if its Wednesday add 4 to the date and return the date in MM/DD/YYYY form.
and so on until Sunday when it will add 0.
So lets say todays Monday, it will return 1/8/2012
And in real dates today's Sunday so it will really return 1/1/2012
Then I just want to call a document.write function to write the MM/DD/YYYY it returns into my HTML document.
Can anybody help me? I can clarify if you need me to...
getDay() returns the day of the week, Sunday = 0, Monday = 1, etc, etc.
So say today was Monday getDay() would return 1, which means daysToAdd would be 5.
Once we know how many days we want to add we can create a new date and add those days. We do this by getting today in milliseconds and then adding the number of days (daysToAdd) in milliseconds.
We convert days to milliseconds by multiplying by 24*60*60*1000 which is the number of milliseconds in a day.
I add 1 to the month because JavaScript returns 0 based month, but for display purposes we want to format it so that January for example is 1 not zero.
function getEndOfWeek() {
var today = new Date();
var weekDay = today.getDay();
// if you want the week to start on Monday instead of Sunday uncomment the code below
//weekDay -= 1;
//if(weekDay < 0) {
// weekDay += 7;
//}
var daysToAdd = 6 - weekDay;
var newDate = new Date(today.getTime() + daysToAdd *24*60*60*1000);
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
var year = newDate.getFullYear();
var formatedDate = month + "/" + day + "/" + year;
return formatedDate;
}
You could implement in your code like so, JavaScript:
$(function() {
$("#TheDate").html(getEndOfWeek());
});
Your HTML would be something like this:
The week ends on <span id="TheDate"></span>.
You can find the jsFiddle here: jsFiddle
If you want to adjust the weekday so that you consider Monday the start of the week instead of Sunday you can do the following after you get the weekDay:
weekDay -= 1;
if(weekDay < 0) {
weekDay += 7;
}
var day = 1000*60*60*24
, nextSunday = new Date(+new Date() + day*(7-((0|(+new Date()/day)%7-3)||7)));
alert(
(101+nextSunday.getMonth()).toString().substr(1) + '/' +
(100+nextSunday.getDate()).toString().substr(1) + '/' +
nextSunday.getFullYear()
)
As fas as adding dates in JavaScipt my "DateExtensions" library does this well enough, I think. You can get it here:
http://depressedpress.com/javascript-extensions/dp_dateextensions/
Once refenced you can call "add()" as a method for any valid date and pass it any of many date parts (second, minutes, days, hours, etc). So assuming "curDate" is a valid JavaScript date object you can add 5 days like this:
newDate = curDate.add(5, "days");
Using a negative value will subtract:
newDate = curDate.add(-5, "days");
Once you get the date you want you can the use the library's dateFormat() method to display it like so:
curDate.dateFormat("MM/DD/YYYY");
There's full documentation at the link.
Integer Values for Day of Week
As for getting the integer value you want, it's actually easier that it looks (and you don't need an "if" just some math). The getDay() method of date returns the day of week with Sunday as "0" and Saturday as "6". So the week, from Sunday, would normally be:
0,1,2,3,4,5,6
First, you want to reverse that scale. That's easily done via subtraction by taking 7 (to total number of members of the set) from the value. This gives you this scale:
-7,-6,-5,-4,-3,-2,-1
We're getting closer. You want the first value to be zero as well. The simplest way (I think) to do this is to get the modulus (remainder) of the value by the total number of members. All this basically does is make "-7" a zero and leave the rest alone giving us this:
0,-6,-5,-4,-3,-2,-1
Almost done. Finally you don't want negative numbers so you need to use the Math.abs() method to eliminate the sign (get the absolute value) leaving us with our desired result:
0,6,5,4,3,2,1
For all the talk the acutual code is pretty compact:
Math.abs((cnt-7)%7)
Wrapping this into the original example gives us:
newDate = curDate.add(Math.abs((curDate.getDay()-7)%7), "days");
Server Vs Client
However take nnnnnn's comment to heart: in JavaScript the getDate() function gets the current date/time of the machine that it's running on - in the case of a web page that's the client, not the server.
If you actually meant the client time them you're set and done. If you really need the server time however that's annoying-to-impossible. If you own the server then it's actually not to hard to set up a rule that includes the current server in a cookie withing each fufilled request (you could then use my cookie library, also at the site above, to access the information!)
It's messier but depending on the server you might also be able to create an old-school server-side include that adds a bit of JavaScript to each page (preferably as a marked replace in the header) that hard-codes the date as a global variable.
You might also create a web service that returns the current server time but the client-overhead for that is insane compared to the data being delivered.
If the server's NOT yours (and you can't get the owner to provide the above) then the only real potential option is to do a straight http call and examine the HTTP "Date" header. Again however the overhead on this is immense compared to the return but it's really the only way. Any system like this would have to be very flexible however as any particular server might not return the date header or might not return it correctly.
Even if it does work understand that you might still not be getting the "server" time - or at least not the server you want. In a tiered architecture, for example an application server might render then page and hand it to a web server to return - you'd be getting the web server time, not the app server. Any number of appliances might also rewrite the headers (for example it's common to use dedicated SSL appliances to offload all the encryption work - these often re-write the headers themselves).
Sorry to get overly technical - JavaScript is definately one area where there's unfortunately rarely a "simple question". ;^)
Good Luck!
PetersenDidIt did a great job answering this question.
He showed how to use a link to update the jQueryUI Datepicker's selected date by one day. His solution was:
$('a#next').click(function () {
var $picker = $("#datepicker");
var date=new Date($picker.datepicker('getDate'));
date.setDate(date.getDate()+1);
$picker.datepicker('setDate', date);
return false;
});
I am trying to modify it to do the same thing for a week or month. According to the set date api I should be able to use "+1m" and "+1w" to skip a month or week. I can't seem to get the code working with anything other than "+1".
Thoughts?
you can use the same code you have.
when you want one week do like this:
date.setDate(date.getDate()+7);
when you want one month you can do:
date.setMonth(date.getMonth()+1);
Try using FireBug script debugging. Might be some JS exception being generated.