Thursday, August 24, 2023
HomeProgrammingProducing UTC/GMT Timestamps in JavaScript

Producing UTC/GMT Timestamps in JavaScript


Introduction

When working with JavaScript, you might typically discover the necessity to generate a timestamp that’s in Common Coordinated Time (UTC) or Greenwich Imply Time (GMT). This can be a widespread requirement in internet growth, particularly when coping with worldwide customers. On this article, we’ll discover the right way to generate a UTC/GMT timestamp utilizing JavaScript.

Understanding UTC and GMT

Earlier than we get into the code, it is essential to know what UTC and GMT are. UTC, or Coordinated Common Time, is the time commonplace utilized in aviation, computing, navigation, climate forecasting, and lots of different fields. It is basically the time on the prime meridian (0° longitude), however with just a few technical variations which are past the scope of this text.

GMT, or Greenwich Imply Time, is the imply photo voltaic time on the Royal Observatory in Greenwich, London. It was as soon as the worldwide time commonplace, however has been largely changed by UTC.

Word: For many sensible functions, particularly in computing, UTC and GMT are thought-about equal.

Producing a UTC/GMT Timestamp

Now that we perceive what UTC and GMT are, let’s examine how we will generate a timestamp in these codecs utilizing JavaScript.

In JavaScript, the Date object is used to work with dates and occasions. The Date.now() technique returns the variety of milliseconds for the reason that Unix Epoch (January 1, 1970 00:00:00 UTC). Nevertheless, worth is just not in UTC or GMT by default. To transform it, we will use the Date.prototype.toUTCString() technique.

This is an instance:

let date = new Date();
let timestamp = date.getTime();
let utcDate = new Date(timestamp);

console.log(utcDate.toUTCString());

While you run this, it would output a string representing the present date and time in UTC, like this:

"Wed, 23 Aug 2023 22:43:21 GMT"

Conclusion

On this Byte, we have realized what UTC and GMT are and the way they’re utilized in programming/computing. We have additionally seen the right way to generate a UTC/GMT timestamp in JavaScript utilizing the Date object and its strategies.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments