facebook

JS Dates can go back or forward about 280,000 years…

JS Dates can go back or forward about 280,000 years…
Average rating: 0
(0 votes)

Thanks! You’ve rated this material!

JS Dates is a tricky subject because of all of the world’s time zones, changing clocks, leap years and other oddities. It is simple to get started with dates in JavaScript, and this article will explain most of what you can do with them. So, let’s start with the fact that JS Dates can go back or forward about 280,000 years…

A Date in JavaScript is an object that represents a date and time. JS Dates can go back or forward about 280,000 years and are accurate to the nearest millisecond (thousandth of a second). Inside the Date object there is just one value which is the number of milliseconds before or after 01 Jan 1970 in UTC time.

The date and time is converted from local time to a UTC-based number inside the Date object. This means you can call methods on Date to find it’s UTC value. You can use other methods to see what that the time is locally too. Whenever you are sending dates to another system (e.g. a web server) it is often wise to send them as UTC.

We recommend:

  • If you need to pass dates around your program, keep them as Date objects if possible.
  • When sending dates to a server or service, use the toISOString to format the date because it is a standard format and uses UTC. Alternatively use the getTime to get the number of milliseconds since 01/01/1970, and this is also in UTC.
  • When receiving dates from a server or service, if you have any control or influence, try to make sure they are sent as an ISO string or milliseconds since 01/01/1970, and then you can pass them as the argument to new Date().
  • Only use the toDateStringtoTimeStringtoUTCString, etc. methods for strings that will be shown to a user of your web page.
  • Be careful when using libraries with calendar controls, and read the documentation about what date format’s they expect to work with.

It is good to be aware of time zones, and that a JavaScript Date is a UTC based date under the hood, even if you create it and query it in the local time zone. Find more examples here.

Learn all you need to know about JavaScript in the Complete JavaScript Handbook by Flavio Copes.

And take a look of the list with the most popular JS open source repositories on GitHub in March!

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

*By submitting this form you agree with our Privacy Policy.

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111