DEV Community

Cover image for Working With Javascript Date & Time: A Cheat Sheet
Jesse Wei
Jesse Wei

Posted on

Working With Javascript Date & Time: A Cheat Sheet

A common task in programming is working with date and time. Javascript Date object provides us with a wealth of methods that are pretty handy and powerful. But using these methods correctly to get the desired result can be challenging.

So I picked the most frequently used methods and put them into this cheat sheet to make your life easier.

Table of Contents


An Overview

When working with dates and times, you'll most likely want to perform addtions/subtractions on your date or time values, transform a value from one type, e.g. number to another, e.g. string, format your date and time strings and so on.

For example, let's say we want a string representation of the time 15 minutes from now. We follow these steps to get the result:

  1. Get the number of milliseconds (nowMs) for now.
  2. Add 15 * 60 * 1000 to nowMs (fifteenMinutesLaterMs).
  3. Convert fifteenMinutesLaterMs to a time string.
  4. Optionally format the time string.

We'll look at this example in more detail later, but as you can see, at the core of solving such problems is understanding what data types you need to perform what operations and which methods help you achieve that.


Cheat Sheet

Here is a list of the methods I find I'm using most of the time. Please note that,

  • All methods, except the constructors new Date() and Date() and static method Date.now(), are instance methods of a Date object.
  • Number of milliseconds refers to the number of milliseconds between January 1, 1970, 00:00:00 UTC and your specified date.
  • To find out more about the methods, check out MDN docs on Date.

Methods returning Date object

  • new Date()

Params: date object/date string/milliseconds/year, month/year, month, day/year, month, day, hours/...

Methods returning number of milliseconds

  • Date.now()
  • getTime()
  • setTime(params)

Params: number of milliseconds

  • setHours(params)

Params: hours/hours, minutes/hours, minutes, seconds/hours, minutes, seconds, milliseconds

  • setMinutes(params)

Params: minutes/minutes, seconds/minutes, seconds, milliseconds

Note: For information on other setSometing() methods, check out MDN docs on Date.

Methods returning date/time string

Returning both date and time in a single string

  • Date() (same as new Date().toString())
  • toString()
  • toLocaleString(params)

Params (optional): locales/locales, options

Returning date string

  • toDateString()
  • toLocaleDateString(params)

Params: locales/locales, options

Returning time string

  • toTimeString()
  • toLocaleTimeString(params)

Params: locales/locales, options


Common Use Cases

Now, let's look at some common use cases of these methods. Please note the values used in the examples below are subject to my timezone and the time the date objects were instantiated, so your values will most likely be different.

Milliseconds to Date

Example:
1670454321367 → 2022-12-07T23:05:21.367Z

Solution:

const date = new Date(1670454321367)
Enter fullscreen mode Exit fullscreen mode

String to Date

Example:
'2022-12-07' → 2022-12-07T00:00:00.000Z
'2022-12-07T00:00' → 2022-12-06T15:00:00.000Z

Solution:

const date1 = new Date('2022-12-07')
const date2 = new Date('2022-12-07T00:00')
Enter fullscreen mode Exit fullscreen mode

Note: Although the two strings passed to Date constructor seem to refer to the same date, two different dates were returned in the example. This is because Date-only strings are treated as UTC, while date-time strings are treated as local.

Year, Month, Day Numbers to Date

Example:
2022, 11, 7 → 2022-12-06T15:00:00.000Z

Solution:

const date = new Date(2022, 11, 7)
Enter fullscreen mode Exit fullscreen mode

Note: Remember month is 0-based and the passed year, month and day numbers are treated as local.

Date to Milliseconds

Example1: current date time
current date time → 1670454321367

Solution:

const ms = Date.now()
Enter fullscreen mode Exit fullscreen mode

Example2: specified date time
2022-12-07T21:00 → 1670414400000

Solution:

const ms = new Date('2022-12-07T21:00').getTime()
// OR
const ms = new Date('2022-12-07').setHours(21, 0, 0)
Enter fullscreen mode Exit fullscreen mode

Example3: specified time of today
21:00 of today → 1670414400000

Solution:

const ms = new Date().setHours(21, 0, 0)
Enter fullscreen mode Exit fullscreen mode

Date to String

Example1:
Wed Dec 07 2022 21:33:20 → 'Wed Dec 07 2022 21:33:20 GMT+0900 (日本標準時)'

Solution:

const str = Date()
// OR
const str = new Date().toString()
Enter fullscreen mode Exit fullscreen mode

Example2:
Wed Dec 07 2022 21:33:20 → '2022/12/7 21:33:20'

Solution:

const str = new Date().toLocaleString()
Enter fullscreen mode Exit fullscreen mode

Example3:
Wed Dec 07 2022 21:33:20 → 'Wed Dec 07 2022'

Solution:

const str = new Date().toDateString()
Enter fullscreen mode Exit fullscreen mode

Example4:
Wed Dec 07 2022 21:33:20 → '2022/12/7'

Solution:

const str = new Date().toLocaleDateString()
Enter fullscreen mode Exit fullscreen mode

Example5:
Wed Dec 07 2022 21:33:20 → '21:33:20 GMT+0900 (日本標準時)'

Solution:

const str = new Date().toTimeString()
Enter fullscreen mode Exit fullscreen mode

Example6:
Wed Dec 07 2022 21:33:20 → '21:33:20'

Solution:

const str = new Date().toLocaleTimeString()
Enter fullscreen mode Exit fullscreen mode

String to Milliseconds

Example:
'21:00' of today → 1670414400000 (your output will be different)

Solution:

const [h, m] = '21:00'.split(':')
const ms = new Date().setHours(h, m, 0)
Enter fullscreen mode Exit fullscreen mode

Milliseconds to string

Example:
1670414400000 → '21:00'

Solution:

const ms = new Date(1670414400000).toLocaleTimeString().slice(0, -3)
Enter fullscreen mode Exit fullscreen mode

Note: For single-digit hours, say 8, toLocaleTimeString() returns 8:00:00 while toTimeString() returns 08:00:00. To get consistent results, I used slice(0, -3) to just drop the last :00.

Get an Offset Time String

Example:
'8:00' → '8:30'

Solution:

const offsetMs = 30 * 60 * 1000
const timeBeforeMs = new Date().setHours(8, 0, 0)
const timeAfterMs = timeBeforeMs + offsetMs
const timeAfterString = new Date(timeAfterMs).toLocaleTimeString().slice(0, -3)
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this post, we looked at some of the most frequently used Javascript data time methods. By playing with the parameters of those methods, e.g. the options parameter of toLocaleSomething() methods, you'll discover that those methods are actually more powerful than I demonstrated here.

As I mentioned, it's important to understand what type of data you want and which methods help you get the correct type of data. And as a bonus tip, I highly recommend you NAME your variables in a way that explicitly conveys information about the type of data they hold. This means myTimeMs is a better name for a variable holding a milliseconds value than myTime.

Finally, when you're not sure about any of the methods, do check out the great MDN docs on Date.

Top comments (0)