Dates
Creating a date
// current date/time let today = new Date(); // specific date let birthday = new Date('December 17, 1995 03:24:00'); let birthday = new Date('1995-12-17T03:24:00'); // the month is 0-indexed let birthday = new Date(1995, 11, 17) let birthday = new Date(1995, 11, 17, 3, 24, 0) // passing epoch timestamp let birthday = new Date(628021800000)
Deconstructing Date Object
const date = new Date(); const [month, day, year] = [date.getMonth(), date.getDate(), date.getFullYear()]; const [hour, minutes, seconds] = [date.getHours(), date.getMinutes(), date.getSeconds()];
Variations
new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
Methods
getDay()
var Xmas95 = new Date('December 25, 1995 23:15:30'); // returns day of the week for the specified date according to local time, where 0 represents Sunday var weekday = Xmas95.getDay(); console.log(weekday); // 1 // returns the day of the month for the specified date according to local time const day = Xmas95.getDate(); console.log(day); // 25
Time-zone specific conversions
Date.toLocaleTimeString()
Returns a string presenting the time portion of given Date instance according to language-specific conventions
// syntax toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) // creating date const event = new Date('August 19, 1975 23:15:30 GMT+00:00'); // US locale console.log(event.toLocaleTimeString('en-US')); // 1:15:30 AM // Italian locale console.log(event.toLocaleTimeString('it-IT')); // 01:15:30
Options Parameter
// creating a date const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // defining options const options = { timeZone: "UTC", timeZoneName: "short" }; console.log(date.toLocaleTimeString("en-US", options)); // "3:00:00 AM GMT" // creating time with specific zone new Date().toLocaleString("en-US", {timeZone: "America/New_York"}) // other time zones const world_timezones = [ 'Europe/Andorra', 'Asia/Dubai', 'Asia/Kabul', 'Europe/Tirane', 'Asia/Yerevan', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Mawson', ... ]
Recommended Format
ISO 8601
YYYY-MM-DD
YYMMDD