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.
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'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
I'd like to add a counter to my website which counts in days. However I'd also like to add a button where this can be reset back to 0.
After searching I found the below code, and all is needed now is the button for it. I'm no Javascript expert so any help would be great.
I used this code to create the counter:
<script type="text/javascript">
//Set the two dates
var startdate=new Date(2013, 11, 16) //Month is 0-11 in JavaScript
today=new Date()
//Get 1 day in milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((today.getTime()-startdate.getTime())/(one_day))+
" days since your last drink!")
</script>
Is there a way I can include a button to reset the start date to the current date (for example if pressed today it would change from 16th of December 2013 to the 19th of December 2013)
Does anyone have any idea how I would do this? I'm fairly new to javascript so just learning the ropes.
Thanks
Gary
#Jonathan has given a good method of achieving this using cookies.This is what most of the sites use to save your preferences.
Another possible way is that you can make use of database to save the startDate for each user and update it accordingly when the reset button is set.The next time you fetch startDate it will be the updated date.You can save it where you are saving his profile information.
If you have small number of users you can also use xml file to store the startDate information and updating it accordingly.
I would go for database or cookies.
Hope it helps
I want to show users how long has been elapsed since they performed an action.
The date+time of the action happening is stored on the server, in the server's timezone. That's what's causing the trouble, since if the user's computer's timezone is 12 hours ahead of the server's timezone, then if the user adds something right now, moment.js will show '12 hours ago' as the output of fromNow() rather than just now.
To try to solve this, I'm trying the following method:
var actionTime = moment( action.timeStamp);//time of when user performed action
var serverTime = moment().zone('-07:00'); //current server time
console.debug( serverTime);//outputs Wed Sep 11 2013 15:19:51 GMT-0700
var timeAgo = serverTime.from( actionTime);
But despite of all this, timeAgo still shows the difference between the client's timezone and the server's timezone (i.e showing '12 hours ago' instead of 'now');
Anyone know how to fix this or what I'm doing wrong?
Ideally, you would want to pass a UTC timestamp from your server to the client. That doesn't mean you have to switch your whole server over to UTC, it just means that you would convert from the time in your database to UTC on the server before sending it over the web. Sure, it would be even better if you actually stored times in UTC, but you said you aren't in a position to make that sort of change right now. But let's just work off the assumption that you can't change anything at all on the server.
We'll also assume that your server is fixed to the UTC-07:00 offset. In real life, this would only be true for places like Arizona that don't follow daylight saving time. So if you are in Los Angeles and are in Pacific Time, then some of your data is based on UTC-07:00, but some of it is based on UTC-08:00. That requires a lot more work if you want to do it in JavaScript.
Let's also assume that the input is already a string in ISO8601 format. (If it's not, then let me know and I will adjust this code.)
var s = "2013-09-11 18:00:00"; // from action.timeStamp
var actionTime = moment(s + "-07:00", "YYYY-MM-DD HH:mm:ssZ");
var timeAgo = actionTime.fromNow();
The reason your other code didn't work is because in the first line, you are affected by the time zone of the browser. The zone setter in the second line just changes the zone for formatting, not changing the actual moment in time.
Also, when you dump a moment to the console for debugging, make sure you format it for output. Otherwise you are just looking at its internal property values, which may or may not make sense directly.
I have solved it in a different way, maybe this option was not possible back when the question was asked, but might be easier now.
I used moment-timezone.js (which requires moment.js 2.6.0+).
I set the default timezone to my server's timezone like this:
moment.tz.setDefault("America/New_York"); // "America/New_York" in my case
and then just use it normally. fromNow() will use the timezone in the client to calculate the time that has passed since that moment.
moment(myDatetime).fromNow();
i had the same issue and used the above comments to modify my code. I did the following to get it resolved:
transform(value: string) {
var time = moment(value).utc();
return moment(time, "YYYYMMDD").fromNow();
}
I was missing the .utc() to convert it before I applied the .fromNow()
Things to note this is being used within a Pipe for Ionic 3 and the above code is from the pipe logic.
I am using the TimeTracker.js from link text to track Page Load times and put them in Google Analytics. Basically what it does is record a start time, and once the page loads it records a end time and then subtracts. These are recored using (new Date()).getTime().
Everything works fine except for instances where the time difference is between 0-100ms. Here I get a massive negative numbers such as -17,183,398,582. Does anyone know what is causing this? Is it got to do with the way Javascript is handling the date substraction or is it something to do with Analytics?
Any help much appreciated. Thanks
Just a guess, but that negative number sounds like it could be linked to Unix epoch time. Example:
var currentTime = new Date().getTime();
currentTime will hold a number such as 1289985468 which represents "GMT: Wed, 17 Nov 2010 09:17:48 GMT".
Perhaps there's a bug in that code you're using.