The problem at hand is to find out the generic timestamp last time it was 12 am in a specific timezone.
e.g. I want timestamp when it was last 12 am in India (IST).
Tried the following:
var IST = new Date(new Date().getTime() + 330*60*1000)
IST.setHours(0);
IST.setMinutes(0);
IST.setSeconds(0);
IST.setMilliseconds(0);
Turns out it returns the last time it was 12 am in GMT.
When you use
new Date()
this gives the date in the current timezone.
When you change your code to:
var UTC = new Date();
UTC.setUTCHours(UTC.getUTCHours());
UTC.setUTCMinutes(UTC.getUTCMinutes());
UTC.setUTCSeconds(UTC.getUTCSeconds());
UTC.setUTCMilliseconds(UTC.setUTCMilliseconds());
now UTC is set to current UTC time. Add time difference for eventual changes in date and set time to 00:00:00
UTC = new Date(UTC.getTime() + 330*60*1000);
UTC.setUTCHours(0);
UTC.setUTCMinutes(0);
UTC.setUTCSeconds(0);
UTC.setUTCMilliseconds(0);
you will get the last UTC 12 am. Add to this the time difference with the required timezone, and you should get the right time.
var IST = new Date(UTC.getTime() + 330*60*1000);
Related
const dt = new Date('2017-12-12');
console.log(format(dt, 'YYYY-MM-DD'));
The above code logs 2017-12-11 in the US, but 2017-12-12 in India.
I followed this github thread here and tried out things but am not getting the desired results.
My expectation is to print the same date irrespective of time zone
Why I need this :
Consider a scenario involving birthdates. If i am giving some input date, it has to be displayed as same date in all regions irrespective of their timezones.
You will need to subtract the time zone offset of your local time zone from the Date instance, before you pass it to format from date-fns. For example:
const dt = new Date('2017-12-12');
const dtDateOnly = new Date(dt.valueOf() + dt.getTimezoneOffset() * 60 * 1000);
console.log(format(dtDateOnly, 'YYYY-MM-DD')); // Always "2017-12-12"
Problem
You want to handle only the date part of the Date instance, because the time part does not make sense for birthdates. However, the Date object does not offer any "date-only" mode. You can access both its date and time parts in the local time zone or UTC. The problem is, that format from date-fns prints the output always in the local time zone.
When you executed the constructor only with the date part:
const dt = new Date('2017-12-12');
The JavaScript engine actually assumed a string in the incomplete ISO 8601 format and perfomed this:
const dt = new Date('2017-12-12T00:00:00.000Z');
It may still look "harmless" to you, but the date instance exposes the value not only in UTC, but also in the local time zone. If you construct the Date instance on the East Coast of the US, you will see the following output:
> const dt = new Date('2017-12-12');
> dt.toISOString()
'2017-12-12T00:00:00.000Z'
> dt.toString()
'Tue Dec 11 2017 19:00:00 GMT-0500 (EST)'
> d.toLocaleString()
'12/11/2017 7:00:00 PM'
Solution
If you know, that format from date-fns reads date and time parts from the date instance in the local time zone, you will need to make your date "looking like" the midnight in your local time zone and not in UTC, which you passed to the Date constructor. Then you will see the year, month and date numbers preserved. It means, that you need to subtract the time zone offset of your local time zone for the specified day. Date.prototype.getTimezoneOffset returns the offset, but with an inverted sign and in minutes.
const dt = new Date('2017-12-12');
// Tue Dec 11 2017 19:00:00 GMT-0500 (EST)
const dtDateOnly = new Date(dt.valueOf() + dt.getTimezoneOffset() * 60 * 1000);
// Tue Dec 12 2017 00:00:00 GMT-0500 (EST)
console.log(format(dtDateOnly, 'YYYY-MM-DD'));
// Prints always "2017-12-12", regardless the time zone it executed in
However, such Date instance can be used only to format the date-only value. You cannot use it for computing date differences, for example, which would need the original and correct UTC value.
Alternative
If you need always the same date-only format and not the format specific to the current locale, you do not need date-fns. You can format the string by the concatenation of padded numbers:
const dt = new Date('2017-12-12');
const year = dt.getUTCFullYear()
const month = dt.getUTCMonth() + 1 // Date provides month index; not month number
const day = dt.getUTCDate()
// Print always "2017-12-12", regardless the time zone it executed in
console.log(year + '-' + padToTwo(month) + '-', padToTwo(day));
// Or use a template literal
console.log(`${year}-${padToTwo(month)}-${padToTwo(day)}`);
function padToTwo (number) {
return number > 9 ? number : '0' + number
}
Only adding the #ferdinand-prantl answer. If you are using the date-fns, you can parse the string date ('2017-12-12') using the parseISO(here) fn from date-fns, which will complete the missing ISO 8601 format with your local time zone. When you use the format fn, you are going to keep the date.
const strDate = '2017-12-12';
const isoDate = parseISO(strDate);
const formattedDate = format(isoDate, 'YYYY-MM-DD');
console.log({strDate, isoDate, formattedDate})
//{
// strDate: '2017-12-12',
// isoDate: 2017-12-12T02:00:00.000Z,
// formattedDate: '2017-12-12'
//}
I am asking the user to input a date and time into my application. The user will input a time based on the timezone they are in. When I save this date and time to my database I want to convert the time to UTC so that when I query by time (which is done in UTC) I can find the entries.
This is what I've currently done :
var date = new Date();
var dateString = "0" + (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
//format date
date = moment(dateString, "MM/DD/YYYY HH:mm a");
date = new Date(date).toISOString();
Where time is the time the user enters (ex if I want to schedule something for 11:00am, time = 11:00am)
When this is saved to the database, it looks like :
ISODate("2016-05-09T11:00:00Z") which is not correct since that is a EST saved as Zulu time.
How can I convert the time (I am using moment) to be saved as the correct Zulu time?
One option would be to use Javascript's built-in UTC functions.
JavaScript Date Reference
getUTCDate() - Returns the day of the month, according to universal time (from 1-31)
getUTCDay() - Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear()- Returns the year, according to universal time
getUTCHours() - Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() - Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() - Returns the minutes, according to universal time (from 0-59)
getUTCMonth() - Returns the month, according to universal time (from 0-11)
getUTCSeconds() - Returns the seconds, according to universal time (from 0-59)
For example,
new Date('2016-05-09 10:00:00')
returns Mon May 09 2016 10:00:00 GMT-0400
new Date('2016-05-09 10:00:00').getUTCHours()
returns 14
UPDATE: Examples (including .toISOString())
If we choose July 4, 2016 # 8:00 PM Eastern Time (GMT-0400), UTC would be July 5, 2016 # 00:00 (midnight):
var date = new Date('2016-07-04 20:00:00')
date.getUTCFullYear = 2016
date.getUTCMonth = 6 (0 base)
date.getUTCDate = 5
date.getUTCHours = 0
date.getUTCMinutes = 0
var date = new Date('2016-07-04 20:00:00')
date.toISOString() = "2016-07-05T00:00:00.000Z" (UTC)
To fix this issue I used the moment-timezone library.
I first set the timezone on the server since it will only be accessed by EST :
moment.tz.setDefault("America/New_York");
Then all I needed to do was set the timezone on the moment object to UTC by :
date = moment(dateString, "MM/DD/YYYY HH:mm a").tz("UTC");
This successfully converts the time from EST to UTC
This is my code:
var feedDataTimestamp = new Date("2014-01-14T00:04:40+0000").getTime();
var parsedDate = new Date(+feedDataTimestamp);
alert(parsedDate.getHours());
but it should print 0, not 1: time is 00:04:40
Because you (according to your Stackoverflow profile) are in Italy, so your time zone is UTC+1.
The time stamp you are inputting is UTC+0.
parsedDate will be in local time.
Use the getUTCHours() method if you want to get UTC time instead of local time.
You set the timezone in the parsed string as +0000 so you seem to want the hours in UTC, use
alert(parsedDate.getUTCHours())
I've created a date in JS like so:
var myDate = new Date('2013-01-01 00:00:00');
I assume JS reads this in as UTC time. But when I do something like myDate.getTime() the timestamp returned was something like 4AM GMT time.
Why is this? And how do I get the date as midnight in UTC time?
At least in Chrome, this works:
var myDate = new Date('2013-01-01 00:00:00 UTC');
It also works if you put GMT instead of UTC. But I don't know if this is cross-browser enough.
I live in India. Hence my timezone is the Indian Standard Time (IST) which is listed in the tz database as Asia/Kolkata. India is 5 hours 30 minutes ahead of GMT. Hence when I execute new Date("2013-01-01 00:00:00") the actual time at GMT is "2012-12-31 18:30:00".
I believe you live in America because you're in the EST timezone (GMT-04:00)? Am I right?
If you want to parse the time at GMT instead of your local timezone then do this:
new Date("2013-01-01T00:00:00+00:00");
Notice the capital T between the date and the time, and the +00:00 at the end. This is the format used to parse a given time in a specific timezone.
Given the date string "2013-01-01 00:00:00" you can convert it to the required format using the following function:
function formatDateString(string, timezone) {
return string.replace(" ", "T") + timezone;
}
Then you can create the date as follows:
new Date(formatDateString("2013-01-01 00:00:00", "+00:00"));
Another way to convert local time to GMT is as follows:
var timezone = new Date("1970-01-01 00:00:00"); // this is the start of unix time
Now that you have your own local timezone as a date object you can do:
new Date(new Date("2013-01-01 00:00:00") - timezone);
All the above methods produce the same date at GMT.
JS reads this with time zone that your computer uses.
You can try use myDate.toUTCString() for get date in UTC time.
If you want get timestamp use myDate.getTime()
Mine works simply by doing this
var datetime= new Date()
However the month is 1 low so you have to add one
Well, you might think that this question has already been asked, but I think it has not. The solutions I've read about all had this "jigsaw puzzle" technique (like getUTCMonth() + getUTCMinutes + ...).
But as I only want to compare the elapsed seconds between two UTC (!) dates, this does not apply.
As everybody knows, you can get the current (non-UTC) date by:
var d = new Date();
var t_millis = d.getTime();
But this is NOT what I want. I'd like to have the current system date in UTC and in milliseconds, so not mess about with strings at all. AFAIK the variable t_millis will contain the millisecond value of the current timestamp in GMT, not UTC.
(Since d is in GMT as well. Unless getTime() does a sort of implicit time zone conversion, i. e. adding the offset BEFORE giving out the milliseconds, but I've never read about that anywhere)
So is there really no other way than adding the offset to the time value?
I'm desperately missing a function like getUTCTimeMillis() known from other languages.
This is an old question but for the sake of the new visitors here is THE CORRECT ANSWER:
Date.now();
It returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
The millisecond value of the time-of-day is going to be the same regardless of your time zone. That is, there are no time zones on planet Earth that differ from one another by a number of milliseconds greater than zero. (They may differ by an integer number of hours or even minutes, but not seconds or milliseconds.)
That said, the value you get back from getTime() is a UTC-relative timestamp. If two web browsers at widely different spots on the globe create a Date object at the same time, they'll both get the same value from .getTime() (assuming the clocks are synchronized, which is of course highly unlikely).
Here: 1338585185539 That's a timestamp I just got from my browser. I'm in Austin, TX, and now it's 4:13 in the afternoon (so that timestamp will be from slightly before that). Plug it into a Date instance on your machine and see what it says.
(edit — for posterity's sake, that timestamp is from 1 June 2012.)
how about:
var now = new Date();
var utc_now = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
console.log('UTC: ' + utc_now) // correct UTC time but wrong timezone!
console.log('UTC (in ms): ' + utc_now.getTime())
I have used this function to solve the problem.
function getUTCNow()
{
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
The getTime function returns the number of milliseconds elapsed since
1 January 1970 00:00:00 in the client timezone.
getTimezoneOffset return offset in minutes between Client timezone and UTC.
offset = offset * 60000; this operation transform minutes in miliseconds.
subtracting the offset get the number of milliseconds elapsed since 1
January 1970 00:00:00 UTC.
To get the timestamp from a date in UTC, you need to take in consideration the timezone and daylight savings for that date. For example, a date in January or in July could mean 1 hour difference.
The option below does just that.
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
It can be used as in:
var date = new Date();
var timestamp = date.getUTCTime();