0

Is there a function or a way to convert a UTC timestamp to a local time timestamp?

I am passing the timestamp to angular moments but the timestamp from the server is in UTC.

SoShine Media
  • 11
  • 1
  • 4

2 Answers2

1

Be aware that a JavaScript timestamp (i.e., a value retrieved from Date.now() or date.getTime()) has no timezone associated with it. It is simply the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. In JavaScript, there is no such thing as local timestamp. In order to convert a timestamp into a date that use the machine-local timezone you simply do the following:

let myTimestamp = Date.now();
let dateInLocalTimezone = new Date(myTimestamp);
Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
  • You're right. I was being a bit loose with my terminology. I will correct above. A JavaScript timestamp is simply the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. There is no timezone associated with it. I will fix my answer. – Andrew Eisenberg Mar 20 '17 at 03:04
0

It's unclear whether the question is about parsing or formatting, or both, or whether you want functions only within angular.js or ionic-framework. The following is for plain ECMAScript.

Is there a function or a way to convert a UTC timestamp to a local time timestamp?

Yes, however it depends on what the timestamp is. If it's a string in ISO 8601 extended format like "2017-03-20T15:45:06Z" then in modern browsers it can be parsed by the built-in parser using either the Date constructor (to create a Date object) or Date.parse (to produce a time value).

If it's in any other format, then it should be manually parsed, either with a small function or library.

Once you have a Date object, it can be formatted in the host timezone using Date methods, see Where can I find documentation on formatting a date in JavaScript?

e.g.

var s = "2017-03-20T12:00:00Z"
var d = new Date(s);

// Browser default, implementation dependent
console.log(d.toString());

// Use toLocaleString with options, implementation dependent and problematic
console.log(d.toLocaleString(undefined,{
  weekday: 'long',
  day: 'numeric',
  month: 'long',
  year: 'numeric',
  hour: '2-digit',
  hour12: false,
  minute: '2-digit',
  second: '2-digit'
}));
Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209