Get the Day, Month, Year from a Timestamp in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 26, 2022

banner

Photo from Unsplash

Get the Day, Month, Year from a Timestamp in JavaScript #

To get the day, month and year values from a timestamp:

  1. Pass the timestamp to the Date() constructor to create a Date object.
  2. Use the getFullYear(), getMonth() and getDate() methods to get the year, month and day values.
index.js
const timestamp = 1643200384959; const date = new Date(timestamp); console.log(date); // 👉️ Wed Jan 26 2022 const year = date.getFullYear(); console.log(year); // 👉️ 2022 const month = date.getMonth(); console.log(month); // 👉️ 0 (January = 0, February = 1, etc) const monthName = date.toLocaleString('default', { month: 'long', }); console.log(monthName); // 👉️ "January" const day = date.getDate(); console.log(day); // 👉️ 26

You can pass a timestamp (in milliseconds) to the Date() constructor to create a Date object.

We used the following 3 date-related methods:

  • Date.getFullYear method - returns a four-digit number representing the year that corresponds to a date.

  • Date.getMonth - returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Yes, unfortunately the getMonth method is off by 1.

  • Date.getDate - returns an integer between 1 and 31 representing the day of the month for a specific date.

Note that the `getMonth` method returns a zero-based value, where January is 0, February is 1, March is 2, etc.

The getFullYear, getMonth and getDate methods return the values according to the visitor's local time, if you need to get the year, month and day according to universal time, use the getUTC* methods instead.

index.js
const timestamp = 1643200384959; const date = new Date(timestamp); console.log(date); // 👉️ Wed Jan 26 2022 const year = date.getUTCFullYear(); console.log(year); // 👉️ 2022 const month = date.getUTCMonth(); console.log(month); // 👉️ 0 (January = 0, February = 1, etc) const monthName = date.toLocaleString('default', { month: 'long', }); console.log(monthName); // 👉️ January const day = date.getUTCDate(); console.log(day); // 👉️ 26

The getUTC* methods return the values according to universal time.

There could be a difference between the output from the get* methods and the getUTC* methods if the visitor's timezone has an offset from UTC (Universal Coordinated Time).
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.