Since Node.js is a cross-platform, open-source JavaScript runtime environment, you can use the Date
object methods getDate()
, getMonth()
, and getFullYear()
to get the current day, month, and year in a Node.js application.
To create a new Date
object, just call its constructor like below:
const today = new Date()
// 2020-11-24T10:20:14.782Z
Now you can call the getDate()
, getMonth()
, and getFullYear()
methods on today
to get the current date, month, and year in Node.js:
const day = today.getDate() // 24
const month = today.getMonth() // 10 (Month is 0-based, so 10 means 11th Month)
const year = today.getFullYear() // 2020
Note that getDate()
, getMonth()
, and getFullYear()
return date and time in local timezone of the computer that the script is running on.
If you want to get the date, month, and year in the universal timezone (UTC), use getUTCDate()
, getUTCMonth()
, and getUTCFullYear()
, as shown in the following example:
const utcDay = today.getUTCDate() // 24
const utcMonth = today.getUTCMonth() // 10 (UTC Month is also 0-based)
const utcYear = today.getUTCFullYear() // 2020
The Date
object also provides methods to get time components like hours, minutes, seconds, and milliseconds in the local timezone as well as in the universal timezone (UTC), as shown below:
const hours = today.getHours() // 15 (0-23)
const minutes = today.getMinutes() // 20 (0-59)
const seconds = today.getSeconds() // 14 (0-59)
const millis = today.getMilliseconds() // 782 (0-999)
// UTC Time
const utcHours = today.getHours() // 10 (0-23)
const utcMinutes = today.getMinutes() // 20 (0-59)
const utcSeconds = today.getSeconds() // 14 (0-59)
const utcMillis = today.getMilliseconds() // 782 (0-999)
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.