Javascript Date Cheatsheet

Introduction:

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

JavaScript stores date as a number of milliseconds since January 01, 1970.

Zero time is January 01, 1970, 00:00:00 UTC.

One day (24 hours) is 86 400 000 milliseconds.

Javascript Get Date Methods:
const today = new Date()
today // Sat Dec 03 2022 11:59:42 GMT+0530 (India Standard Time)

//Get Date Methods
today.getDate() //3
today.getDay() //6
today.getMonth() //11
today.getFullYear() //2022
today.getYear() //122
today.getHours() //11
today.getMinutes() //59
today.getSeconds() //42
today.getMilliseconds() //885
today.getTime() //1670048982885
today.getTimezoneOffset() //-330
UTC – Coordinated Universal Time:
const today = new Date() 
today // Sat Dec 03 2022 11:59:42 GMT+0530 (India Standard Time) 

//UTC - Coordinated Universal Time
today.getUTCDate() //3 
today.getUTCDay() //6 
today.getUTCMonth() //11 
today.getUTCFullYear() //2022 
today.getUTCHours() //6
today.getUTCMinutes() //29
today.getUTCSeconds() //42
today.getUTCMilliseconds() //885
Javascript Set Date Methods:
const today = new Date() 
today // Thu Dec 08 2022 12:19:36 GMT+0530 (India Standard Time)

//Set date methods
today.setDate(8) //Set the day as a number (1-31)
today.setMonth(5) // Set the month (0-11)
today.setFullYear(2025) // Set the year (Optionally month and day)
today.setHours(13) // Set the hour(0-23)
today.setMinutes(45) //Set the minutes(0-59)
today.setSeconds(25) //Set the seconds(0-59)
today.setMilliseconds(350) // Set the 11 seconds (0-999)
today.setTime(40) // Set the time (mili seconds since January 1, 1970)
Date String Methods:
const today = new Date() 
today // Sat Dec 03 2022 12:26:18 GMT+0530 (India Standard Time)

//Date string methods
today.toString() //'Sat Dec 03 2022 12:26:18 GMT+0530 (India Standard Time)'
today.toDateString() //'Sat Dec 03 2022'
today.toLocaleString() //'12/3/2022, 12:26:18 PM'
today.toGMTString() //'Sat, 03 Dec 2022 06:56:18 GMT'
today.toUTCString() //'Sat, 03 Dec 2022 06:56:18 GMT'

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories