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.

asked Mar 20, 2017 at 2:17
1
  • What does the UTC timestamp look like? Commented Mar 20, 2017 at 2:20

2 Answers 2

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);
answered Mar 20, 2017 at 2:24
1
  • 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. Commented Mar 20, 2017 at 3: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'
}));

answered Mar 20, 2017 at 4:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.