Convert milliseconds into UTC date object with UTC Time Zone - javascript

I am trying to convert milliseconds into UTC date object as below -
var tempDate = new Date(1465171200000);
// --> tempDate = Mon Jun 06 2016 05:30:00 **GMT+0530 (India Standard Time)** {}
var _utcDate = new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate(), tempDate.getUTCHours(), tempDate.getUTCMinutes(), tempDate.getUTCSeconds());
//--> _utcDate = Mon Jun 06 2016 00:00:00 **GMT+0530 (India Standard Time)** {}
Time is resetting to UTC time but Time Zone is still coming as GMT+0530 (India Standard Time).
Is there any sure shot approach to convert milliseconds into UTC date object with UTC Time Zone?

Quoting from this answer (that I suggest you to read completely):
There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation.
As time zone is not stored in the Date object there is no way to set it.
I see two options:
the first is to make use of a library (as suggested in the answer above). Quite popular now is Moment.js
the second (pure JavaScript - if it's a viable solution in your context):
Do the "time math" in your local timezone.
When you're ready to switch to UTC use toUTCString() method.
Of course you'll end up with a string as this let you store the time zone as long as the date time value.
As you won't be able to manipulate the date time as a Date object from now on this must be the last step.
var tempDate = new Date(1465171200000);
// Mon Jun 06 2016 05:30:00 GMT+0530
// Do your date time math here
// using the Date object's methods
var utcDateAsString = tempDate.toUTCString();
// Mon Jun 06 2016 00:00:00 GMT

You say:
Time is resetting to UTC time but Time Zone is still coming as GMT+0530 (India Standard Time). Is there any sure shot approach to convert milliseconds into UTC date object with UTC Time Zone?
But I think you misunderstand what is occurring. When you pass a number to the Date constructor as in:
new Date(1465171200000)
is it assumed to be milliseconds since the ECMAScript epoch (1970-01-01T00:00:00Z), so a Date object is created with that value as its internal time value. So Date objects are inherently UTC.
When you write that to a string, internally a human readable date string is generated based on the host timezone setting, which is why you see a date for GMT+0530 (that is your host system timezone setting). The Date object itself does not have a timezone, it's always UTC.
When you then use UTC values to create a "local" Date using:
new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), ...)
then the host timezone is used to generate a UTC time value equivalent to a "local" date for the associated values. You've effectively subtracted your timezone offset from the original time value so it now represents a different moment in time. You can get exactly the same result doing:
var d = new Date(1465171200000);
d.setMinutes(d.getMintues() + d.getTimezoneOffset());
which just shows a bit more clearly what's going on. Note that ECMAScript timezone offsets are in minutes and have the opposite sense to UTC, that is, they are negative (-) for east and positive (+) for west. So an offset of UTC+05:30 it is represented as -330 and you need to add it to "shift" a Date rather than subtract it.
var tempDate = new Date(1465171200000);
var _utcDate = new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate(), tempDate.getUTCHours(), tempDate.getUTCMinutes(), tempDate.getUTCSeconds());
console.log('Direct conversion to Date\ntempDate: ' + tempDate.toString());
console.log('Adjusted using UTC methods\n_utcDate: ' + _utcDate.toString());
tempDate.setMinutes(tempDate.getMinutes() + tempDate.getTimezoneOffset());
console.log('Adjusted using timezoneOffset\ntempDate: ' + tempDate.toString());
However, I can't understand why you want to do the above. 1465171200000 represents a specific moment in time (2016-06-06T00:00:00Z), adjusting it for every client timezone means it represents a different moment in time for each client with a different timezone offset.

If you create a Date from a Number, the local timezone is the one considered. But if you want to see what a timestamp would mean with the hours corrected for UTC, you could use a helper as such:
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
The usage would be:
var date = (1465171200000).toUTCDate();

Related

Why does Javascript show me the wrong date?

Consider the following date object which is created in JavaScript.
var date = new Date("2017-09-07T16:46:06.000Z");
This date object should be equivalent to Sep 7 2017 4:46:06 PM
However, in the browser console, when I type the following:
console.log(date);
The following is returned:
Fri Sep 08 2017 02:46:06 GMT+1000 (E. Australia Standard Time)
The time is wrong. (It actually is today's date, but the time is completely wrong).
Key points of confusion:
My computer timezone is set to GMT+1000 (Australia/Brisbane)
When I created the date object, I did not specify the timezone, therefore it should conform to my systems timezone
When I log the date object to the console, it is still using GMT+1000 (Australia/Brisbane) but the date is different
When you created the date, you did specify a timezone. That Z at the end means Zulu or Greenwich Mean Time. Your computer is 10 hours off from GMT, so it adjusts to your local timezone for display.
If you want the date to be in your local time zone, remove the Z
var date = new Date("2017-09-07T16:46:06.000Z");
So it looks like the Z at the end of your date string is meant to represent UTC or Zulu time
var date = new Date("2017-09-07T16:46:06.000");
should be the correct solution

Javascript date toISOSstring/toJSON one day backwards

I store two dates. First date is the current day and the second one is a future date. To convert those dates into format year-month-day I use toISOSstring function. However usually (but not always) the current date is changed one day backwards.
I also tried to use toJSON function instead. But nothing has changed.
season.from = "Sun Apr 02 2017 18:29:52 GMT+0200 (CEST)"
season.to = "Fri Apr 21 2017 18:29:52 GMT+0200 (CEST)"
var date1 = new Date(season.from);
var date2 = new Date(season.to);
season.from = date1.toISOString().slice(0,10);
season.to = date2.toISOString().slice(0,10);
console.log(season.from); // one day backwards (e.g. 2017-04-01 not 2017-04-02)
console.log(season.to); // proper date somewhere in the future
Your original time strings are in local time, or at least they have a time zone specification. But toISOString returns the UTC time:
The timezone is always zero UTC offset, as denoted by the suffix "Z"
In the case of your GMT+02 time zone, this means the date/time returned by toISOString is two hours "earlier" than the local time. In some cases this can be a time before midnight, and this can render a different date as well.
The implementation of the toJSON method depends on toISOString, so it has the same behaviour.
Work-around
You could use toLocaleDateString('se'), which uses your local time, and formats according to Swedish standards, i.e. YYYY-MM-DD, so you don't even need to slice it. There are some other country codes you could specify to have the same.

Why is Date("2014-04-07") parsed to Sat Apr 05 2014 17:26:15 GMT-0500 (CEST)?

I'm creating dates like this:
var StartDate = new Date(data.feed.entry[i].gd$when[j].startTime);
When a date string is received specifying date and time in the form:
"2014-04-12T20:00:00.000-05:00"
Date() interprets this perfectly fine returning:
Sat Apr 12 2014 19:00:00 GMT-0500 (CDT)
However, when the date string is received with no time information in the form:
"2014-04-07"
then Date() is interpreting it as:
Sat Apr 05 2014 19:00:00 GMT-0500 (CDT)
Looks like Date() is taking the -07 as the time and I have no clue where is it getting the date as 05. Any idea what might be the problem?
Could it be, somehow, Date() is interpreting a different time zone because in the first string the time zone is determined at the very end but in the "all day" event there is no indication of the time zone.
Has anybody found this issue? If yes, how did you solve it?
UPDATE: After researching a little bit more this parsing issue I noticed something very weird:
The following statement:
new Date("2014-4-07")
would return Mon Apr 07 2014 00:00:00 GMT-0500 (CDT) which is correct, but the following one:
new Date("2014-04-07")
returns Sun Apr 06 2014 19:00:00 GMT-0500 (CDT) which is the wrong one. So, for whatever reason, seems like the padding zeros affect the way the date is parsed!
You're using the Date() function wrong.
It only accepts parameters in the following formats.
//No parameters
var today = new Date();
//Date and time, no time-zone
var birthday = new Date("December 17, 1995 03:24:00");
//Date and time, no time-zone
var birthday = new Date("1995-12-17T03:24:00");
//Only date as integer values
var birthday = new Date(1995,11,17);
//Date and time as integer values, no time-zone
var birthday = new Date(1995,11,17,3,24,0);
Source: MDN.
The Date() function does not accept timezone as a parameter. The reason why you think the time-zone parameter works is because its showing the same time-zone that you entered, but that's because you're in the same time-zone.
The reason why you get Sat Apr 05 2014 19:00:00 GMT-0500 (CDT) as your output for Date("2014-04-07" ) is simply because you used it in a different way.
new Date(parameters) will give the output according to the parameters passed in it.
Date(parameters) will give the output as the current date and time no matter what parameter you pass in it.
Prior to ES5, parsing of date strings was entirely implementation dependent. ES5 specifies a version of ISO 8601 that is supported by may browsers, but not all. The specified format only supports the Z timezone (UTC) and assumes UTC if the timezone is missing. Support where the timezone is missing is inconsistent, some implementations will treat the string as UTC and some as local.
To be certain, you should parse the string yourself, e.g.
/* Parse an ISO string with or without an offset
** e.g. '2014-04-02T20:00:00-0600'
** '2014-04-02T20:00:00Z'
**
** Allows decimal seconds if supplied
** e.g. '2014-04-02T20:00:00.123-0600'
**
** If no offset is supplied (or it's Z), treat as UTC (per ECMA-262)
**
** If date only, e.g. '2014-04-02', treat as UTC date (per ECMA-262)
*/
function parseISOString(s) {
var t = s.split(/\D+/g);
var hasOffset = /\d{2}[-+]\d{4}$/.test(s);
// Whether decimal seconds are present changes the offset field and ms value
var hasDecimalSeconds = /T\d{2}:\d{2}:\d{2}\.\d+/i.test(s);
var offset = hasDecimalSeconds? t[7] : t[6];
var ms = hasDecimalSeconds? t[6] : 0;
var offMin, offSign, min;
// If there's an offset, apply it to minutes to get a UTC time value
if (hasOffset) {
offMin = 60 * offset / 100 + offset % 100;
offSign = /-\d{4}$/.test(s)? -1 : 1;
}
min = hasOffset? +t[4] - offMin * offSign : (t[4] || 0);
// Return a date object based on UTC values
return new Date(Date.UTC(t[0], --t[1], t[2], t[3]||0, min, t[5]||0, ms));
}
An ISO 8601 date string should be treated as UTC (per ECMA-262), so if you are UTC-0500, then:
new Date('2014-04-07'); // 2014-04-06T19:00:00-0500
The behaviour described in the OP shows the host is not compliant with ECMA-262. Further encouragement to parse the string yourself. If you want the date to be treated as local, then:
// Expect string in ISO 8601 format
// Offset is ignored, Date is created as local time
function parseLocalISODate(s) {
s = s.split(/\D+/g);
return new Date(s[0], --s[1], s[2],0,0,0,0);
}
In your function you can do something like:
var ds = data.feed.entry[i].gd$when[j].startTime;
var startDate = ds.length == 10? parseLocalISODate(ds) : parseISOString(ds);
Also note that variables starting with a capital letter are, by convention, reserved for constructors, hence startDate, not StartDate.
(I would add a comment but i don't have 50 rep yet)
See what
new Date().getTimezoneOffset()
returns, I would expect a big negative value, that would be the only reasonable explanation to your problem.
I have had some trouble with date conversions in the past, in particular with daytime saving timezones, and as work around i always set the time explicitly to midday (12:00am). Since I think you were using knockout, you could just make a computed observable that appends a "T20:00:00.000-05:00" or the appropiate time zone to all "day only" dates

How to update the date to the current date for UTC -8

I want to display a UTC date using this JavaScriptcode on my webpage.
<script>
function myDate()
{
var now = new Date();
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
var x = document.getElementById("demo");
x.innerHTML=d;
}
</script>
With this code I am getting UTC date displayed as a local string as follows: "Thu Jul 04 2013 00:00:00 GMT+0530 (India Standard Time)"
I do not want display the string with a local time offset (GMT+0530 (IST)), instead I want the time to appear as UTC string format
The date returned by different browser are of different format
to remove GMT OFFSET from date you can use replace
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
d = d.toString().replace(/GMT.+/,"");
Firstly, the problem is that you are instantiating a local Date object by passing in the UTC year, month and day. This then creates a local Date with the values provided. by doing this you might be creating an incorrect date based on whether you want it to be UTC or local. IN your case, if you want var now as UTC, the way you are currently instantiating is incorrect as its in local time.
Anyway, dates can be tricky in in JavaScript, so I would consider using Moment.js for this
It's a fantastic library that provides all of the functions for manipulating and converting JavaScript dates that you could ever need.
For example with moment you can just do the following:
var now = moment(); // current date and time in local format
var nowAsUTC = now.utc(); // current local date and time converted to UTC
var alsoNowAsUTC = moment.utc() // same as the line above, but staring in UTC
console.log(nowUTC.format("DD/MM/YYYY, hh:mm:ss"))// prints a pretty UTC string
Hmmm.. Are you sure you want to display UTC-8? I will take a guess that you are really wanting to convert the time to US Pacific time zone. That is not always UTC-8. Sometimes it is UTC-8, and sometimes it is UTC-7.
If you're not actually in the US Pacific Time zone, the only way to do this reliably in JavaScript is with a library that implements the TZDB database. I list several of them here.
For example, using walltime-js library, you can do the following:
var date = new Date();
var pacific = WallTime.UTCToWallTime(date, "America/Los_Angeles");
var s = pacific.toDateString() + ' ' + pacific.toFormattedTime();
// output: "Fri Apr 26 2013 5:44 PM"
You can't just add or subtract a fixed number, because the target time zone may use a different offset depending on exactly what date you're talking about. This is primarily due to Daylight Saving Time, but also because time zones have changed over time.

JS get date in UTC time

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

Categories

Resources