Borislav Hadzhiev
Wed Jan 26 2022·2 min read
Photo by Jacob Morrison
To get the day, month and year values from a timestamp:
Date()
constructor to create a Date
object.getFullYear()
, getMonth()
and getDate()
methods to get the
year, month and day values.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.
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.
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.
get*
methods and the getUTC*
methods if the visitor's timezone has an offset from UTC (Universal Coordinated Time).