I have a filter that i use to convert date to UTC date.
.filter('utc', function(){
return function(val){
var date = new Date(val);
return new Date(date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),date.getTimezoneOffset());
};
})
So when i give the date 2016-06-18
It returns the date like this Sat Jun 18 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
The date is correct but its not reflecting the correct timezone.
I want it to return in UTC timezone, like Z at the end
A few things:
The
Date
constructor does not have a parameter that accepts a time zone offset. The parameter followingseconds
ismilliseconds
. Refer to the MDN reference.You should not pass UTC-based values into the
Date
constructor where local-based values are expected. Doing so will have the effect of tracking a completely different point in time. You may think you're adjusting for time zone offset, but you are not.The
Date
object always has the following behaviors:It tracks a single value, as returned by
.valueOf()
(inherited fromObject.valueOf
), or by.getTime()
. That value is the number of milliseconds elapsed since Midnight at the start of Jan 1, 1970, in UTC (ignoring leap seconds).The vast majority of input and output functions work with the local time zone - that is, the time zone that is set by the computer where the code is running. The functions that work with UTC typically have
"UTC
" in their name.It is not possible to get the
Date
object to use a different time zone. Any solution that claims otherwise is not considering edge cases. In particular, "epoch-shifting" is a common approach that is fundamentally wrong, when used in isolation. (Passing UTC values into local-time parameters is one implementation of epoch shifting.)If you're looking for a quick solution, consider
.toUTCString()
or.toISOString()
..toLocaleString(undefined, { timeZone: 'UTC'})
Moment.js is a very common library for dealing with these sorts of issue, and fills in a lot of gaps that the
Date
object has. Local-to-UTC is done like this:moment
object), which provides a layer of safety that you just can't get with theDate
object alone.Note that in your question you did not at all state what was in the
val
variable. Depending on whether that is a number, or a string, and what format that string is in, the parsing behavior of theDate
object may change considerably.You can use Date.prototype.toISOString() for this.
You can modify your function to return