Skip to content Skip to sidebar Skip to footer

How To Make The Timezone Of Date To UTC

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.getUTCFu

Solution 1:

A few things:

  • The Date constructor does not have a parameter that accepts a time zone offset. The parameter following seconds is milliseconds. 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 from Object.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().

    • Some browsers may also support the ECMAScript Internationalization API and let you do: .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(input, inputFormat).utc().format(outputFormat)
    
    • Note that moment does a lot of its magic via epoch-shifting, but it hides this via a public API and new object type (a moment object), which provides a layer of safety that you just can't get with the Date 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 the Date object may change considerably.


Solution 2:

You can use Date.prototype.toISOString() for this.

You can modify your function to return

return new Date(date.getUTCFullYear(),
                date.getUTCMonth(),
                date.getUTCDate(),
                date.getUTCHours(),
                date.getUTCMinutes(),
                date.getUTCSeconds(),date.getTimezoneOffset()).toISOString();

Post a Comment for "How To Make The Timezone Of Date To UTC"