Working With Javascript Date & Time: A Cheat Sheet
Tags: javascript, datetime
Published: 2022-12-09 01:06:57

A common task in programming is working with date and time. Javascript [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](#an-overview)
- [Cheat Sheet](#cheat-sheet)
  * [Methods returning Date object](#methods-returning-date-object)
  * [Methods returning number of milliseconds](#methods-returning-number-of-milliseconds)
  * [Methods returning date/time string](#methods-returning-date-time-string)
- [Common Use Cases](#common-use-cases)
  * [Milliseconds to Date](#milliseconds-to-date)
  * [String to Date](#string-to-date)
  * [Year, Month, Day Numbers to Date](#year--month--day-numbers-to-date)
  * [Date to Milliseconds](#date-to-milliseconds)
  * [Date to String](#date-to-string)
  * [String to Milliseconds](#string-to-milliseconds)
  * [Milliseconds to string](#milliseconds-to-string)
  * [Get an Offset Time String](#get-an-offset-time-string)
  * [Conclusion](#conclusion)

---


## 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales)/locales, [options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options)

**Returning date string**

- toDateString()
- toLocaleDateString(params)

Params: [locales](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales)/locales, [options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options)

**Returning time string**

- toTimeString()
- toLocaleTimeString(params)

Params: [locales](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales)/locales, [options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#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)
```

### 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')
```

_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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)._

### Year, Month, Day Numbers to Date

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

**Solution:** 

```
const date = new Date(2022, 11, 7)
```

_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()
```

**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)
```

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

**Solution:** 

```
const ms = new Date().setHours(21, 0, 0)
```

### 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()
```

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

**Solution:** 

```
const str = new Date().toLocaleString()
```

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

**Solution:** 

```
const str = new Date().toDateString()
```

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

**Solution:** 

```
const str = new Date().toLocaleDateString()
```

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

**Solution:** 

```
const str = new Date().toTimeString()
```

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

**Solution:** 

```
const str = new Date().toLocaleTimeString()
```

### 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)
```

### Milliseconds to string

**Example:**
1670414400000 → '21:00'

**Solution:**

```
const ms = new Date(1670414400000).toLocaleTimeString().slice(0, -3)
```

_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)
```

---


## 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).