Javascript moment - timezone, difference between dates in different time zones - javascript

I have:
var now = moment.format(); //get current time
var days = 5; //days I need to subtract from time(then)
var then = '05/02/2016 12:00 am';
Now I need to get difference between now and then substract(-) 5 days but in +0000 so GMT +0.
so now must be in user localtime and then must be at +0000 GMT.
How I can get difference between this dates in days, hours, minutes, seconds?
I try:
var now = moment().format();
var then = moment('05/02/2016 12:00 am').utcOffset(+0000).format();
then = moment(then).subtract(5,'days');
d = moment.utc(moment(now).diff(moment(then))).format("DD HH:mm:ss");
but I get result- which is wrong...
"27 18:48:55"

The problem is that you're trying to use a time difference as a time. You need to use moment.duration() with the return value of the diff. You should also call then.diff(now) to get a positive difference. There were also some unnecessary calls to .format() and moment() that I removed.
var now = moment();
var then = moment('05/02/2016 12:00 am').utcOffset(+0000).subtract(5, 'days');
var duration = moment.duration(then.diff(now));
console.log(duration.days(), duration.hours(), duration.minutes(), duration.seconds());
logs
4 3 15 46

Related

Getting same unix time stamp for two different times in javascript

I had two ical format timestamps and I want to convert them to normal time first and then to unix time.
Here this is the function I've been using to convert normal time to unix timestamp:
var normal_to_unix = function (date_string) {
var date = new Date(date_string);
return date.getTime() / 1000;
}
This function is fine since date is already in UTC and I need not do any conversions.
Now this is the function I've been using to convert ical time to unix time. The ical time in my case is like "20180603T150000Z".
var ics_to_unix = function (ics_string) {
var year = ics_string.slice(0, 4);
var month = ics_string.slice(4, 6);
var date = ics_string.slice(6, 8);
var hours = ics_string.slice(9, 11);
var minutes = ics_string.slice(11, 13);
var seconds = ics_string.slice(13, 15);
var milliseconds = 0;
console.log(year, month, date, hours, minutes, seconds, milliseconds); // This is example output 2018 06 03 15 00 00 0
return normal_to_unix((new Date(year, month, date, hours, minutes, seconds, milliseconds)).toDateString())
}
Now the problem is I'm getting the same unix time for "20180603T150000Z" and "20180603T160000Z" which are supposed to give different timestamps and it is 1530576000 for both of them.
Is there anything that I'm missing ? Thanks in advance.
Please have a look at this for live example
Several points here:
The toDateString() method returns the date portion of a Date object in human readable form in American English. For your example it is `Tue Jul 03 2018', perhaps that is not what you want.
new Date creates date in your local timezone, which could play well if you use it together with toString(), which will also return the string for date in your local timezone. But it will be subject to daylight saving changes, so I'd avoid using that method.
Another thing I'd like to avoid converting back and forth between strings and dates, since it does a lot of unnecessary computations.
I'd suggest to use the following:
var ics_to_unix = function (ics_string) {
var year = parseInt(ics_string.slice(0, 4));
var month = parseInt(ics_string.slice(4, 6)) - 1; // Jan is 0
var date = parseInt(ics_string.slice(6, 8));
var hours = parseInt(ics_string.slice(9, 11));
var minutes = parseInt(ics_string.slice(11, 13));
var seconds = parseInt(ics_string.slice(13, 15));
return Date.UTC(year, month, date, hours, minutes, seconds) / 1000;
}
I have added explicit conversion of strings to numbers, adjusted the month to match what is used in javascript and also removed the extra call.

moment.js timezone get milliseconds

I'm trying to get number of days passed. I'm storing epoch (milliseconds) for date.
I'm reading startDate from database (date value of first record) in milliseconds and I want to find current epoch in specified timezone.
I tried this:
var startDate = rows[0]['MIN_DATE'];
var endDate = moment().tz("America/New_York");
Then to calculate difference, I used:
var oneDay = 24 * 60 * 60 * 1000;
var daysCount = Math.ceil((endDate - startDate) / (oneDay));
The value of startDate is:
1522821600000 which is: Wednesday, April 4, 2018 2:00:00 AM GMT-04:00 DST
The value of endDate is:
Moment_d: Wed Apr 04 2018 22:24:45 GMT-0400 (EDT)_isAMomentObject: true_isUTC: true_isValid: true_locale: Locale_offset: -240_pf: Object_z: Zone__proto__: Object
The value of daysCount is 2, how?
How can I get milliseconds instead of object from:
moment().tz("America/New_York");
To directly answer your question, use .valueOf() to get the value of moment.tz("America/New_York")
var endDate = moment.tz("America/New_York").valueOf()
I'm having difficulty understanding your question, but I believe you're trying to get the difference between the days considering the correct timezone. The following gives an accurate result using .diff() (https://momentjs.com/docs/#/displaying/difference/)
var timeZone = "America/New_York"
var startDate = 1522821600000
var momentStartDate = moment.tz(startDate,timeZone)
var momentEndDate = moment.tz(timeZone)
alert(momentEndDate.diff(momentStartDate, 'days') );
Use fromNow() function. It is very straight-forward.
Do like this :
moment(date).fromNow();
It will give you number of days passed if date is past as well as number of days to go if date is future.
Below are is example:
var date = 1522821600000; // your date
console.log(moment(date).fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Solved this with following statement:
var endDate = moment().tz("America/New_York").valueOf();

How to subtract hours within object in Javascript

I need to calculate work hours between two Date. I set up two date.
var startDate = new Date("2/25/2017 20:30");
var endDate = new Date ("3/28/2017 20:58");
I set up days like objects in which i have work start and work end.
var monday = {"start":"09:00", "end":"17:00"};
var tuesday = {"start":"09:00", "end":"17:00"};
var wednesday = {"start":"09:00", "end":"17:00"};
var thursday = {"start":"09:00", "end":"17:00"};
var friday = {"start":"08:00", "end":"13:00"};
var saturday = {"start":"08:00", "end":"11:00"};
var sunday = {"start":"08:00", "end":"09:00"};
Then i put all objects in array:
var workDays = [monday, tuesday, wednesday, thursday, friday, saturday, sunday];
I don't know how to subtract hours in each day. For example, in monday: 17:00 - 09:00 = 8 hours.
I tried this:
var mondayStart = monday.start;
var mondayEnd= monday.end;
In console i get right start and end time of monday object, but i have problem with subtraction.
var mondayDifference = mondayEnd - mondayStart;
console.log(mondayDifference);
But, in console i get: NaN (not a number).
I'll be thankfull for any hints or help.
If you are given the real case not only POC, parseInt will be enough to get the difference
var mondayDifference = parseInt(monday.end) - parseInt(monday.start);
// "17:00" will be 17 ..so on

Unix offset with fullCalendar difference

I want to place a check when I'm getting a momentjs instance through fullCalendar.
I'm at the eventRender callback
var calendar = $('#calendar').fullCalendar('getCalendar');
var atime = calendar.moment();
var atime_h = atime.format("HH:mm");
atime = atime.unix();
var start = calendar.moment(event.start);
var start_u = start.unix();
var start_h = start.format("HH:mm");
console.log(atime);
console.log(atime_h);
console.log(start_u);
console.log(start_h);
Now what that logs is this:
1408024477
15:54
1407888000
00:00
1408024477 == Thu Aug 14 15:54:37 2014 == is correct
But 1407888000 == Wed Aug 13 02:00:00 2014, where I would expect 00:00 instead of 02:00
So there's a difference between the event .unix()/format.() and the moment I created.
Anyone got a clue what's going on?
Edit:
So what happens is that if I create two new moments: moment() and a moment().utc(), I get the same timestamp for both. But when I then display them, there is a difference of two hours.
The .utc one returns two hours in the past, the one without the correct one for me. The timestamp is not two hours back.
But with the event.start (which has _isUTC=true, the timestamp is two hours in the future (!), and it displays it correct when formatted.
So maybe I need to have my event.start to be not UTC and two hours back somehow?
Edit by request in comment, this is what I use now:
var start = calendar.moment(event.start);
console.log(start);
start_utc = new Date(start.year(), start.month(), start.date(), start.hour(), start.minute(), start.second());
var start = calendar.moment(start_utc);
console.log(start);
Try converting your event.start date to utc first, here's how to do it in vanilla js:
start_utc = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
Then you can call .unix() on it and it should give you the expected timestamp.

JavaScript New Date()

I have the following JavaScript code but for some reason time is not including minutes:
var austDay = $("#<%= hiddenFieldTime.ClientID %>").val().split(" ");
var year = austDay[0];
var months = austDay[1];
var days = austDay[2];
var time = austDay[3];
var timeUntil = new Date(parseInt(year), parseInt(months),
parseInt(days), parseInt(time));
When I debug using firebug these are my value:
$("#ctl00_hiddenFieldTime").val() = "2011, 5, 6, 14:20:00"
year = "2011,"
months = "5,"
days = "6,"
time = "14:20:00"
timeUntil = Date {Mon Jun 06 2011 14:00:00 GMT-0400 (Eastern Daylight Time)}
As you can see, timeUntil is set to 14:00:00 instead of 14:20:00
parseInt(time) is the problem
Here are the few dates initialization format
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
According to the Mozilla documentation for Date, the following constructors are supported:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
This means that in your constructor, when you pass parseInt(time), that parameter is only used for the hour parameter. You need to pass a separate parameter for minutes, and yet another one if you happen to want seconds.
Also, you should always pass a base parameter to parseInt, like so:
parseInt(hours, 10)
Otherwise when you go to parse a value with a leading 0 such as parseInt('08'), the value will be interpreted as an octal number.
Your last conversion is going to drop everything after the colon:
parseInt("14:20:00"); // 14
The whole conversion is rather bloated, I suggest trying to format the string initially in a format you can pass as is to JS's Date constructor, which will make life easier.
parseInt ("14:20:00") returns 14

Categories

Resources