Dates
Intro
- This tutorial covers JavaScript Dates.
- It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript file and view the variable or expression values either with console.logs or using the VS Code Debug sidebar.
- The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate file or folder for each tutorial, including the To-Do List example project. The Readme file has instructions on how to run the code.
1. The Date standard built-in object
- Date is a JavaScript standard built-in object. It is a global object attached to the window global object.
- Date consists of a constructor function to create Date objects, and static and instance properties and methods for working with date objects.
Timestamps
- Unix Epoch: The Unix operating system was created in the early 1970s. The Unix timestamp is the number of seconds since 1/1/1970, which is known as the Unix epoch.
- The JavaScript timestamp is the same except it is the number of milliseconds since Jan 1, 1970.
- Date objects hold the date's timestamp value.
- If you need to display a date object or store it in a database, use Date methods to return its timestamp number or to convert it to a date string.
Time zones
- UTC: The UTC time zone is the Coordinated Universal Time. It is equivalent to Greenwich Mean Time.
- Time zones are expressed as positive or negative offsets from UTC.
- If you don't specify the time zone, some Date methods use UTC as the default time zone, while others use the system's local time zone. For backend applications (e.g., a web server) local time is the server's time setting. For front end applications local time is the web browser's time setting.
2. Create Date objects
- JavaScript does not have a data type for dates or a date literal syntax.
- Instead you have to create an object.
- Date objects are instantiated by calling the Date constructor function with the new operator:
let dateObj = new Date('Dec 31, 2025 UTC');
- If no argument is passed in, the current date and time are used for the object.
dateObj = new Date();
- To specify a date, pass in a date string, timestamp, or number arguments.
- The below examples set the date object to the same value: Dec 31, 2025, UTC.
dateObj = new Date(1767139200000); dateObj = new Date('Dec 31, 2025 UTC');
dateObj = new Date('Dec 30, 2025, 16:00:00 PST');
dateObj = new Date('Dec 30, 2025, 19:00:00 EST'); dateObj = new Date(2025, 11, 30, 16, 0, 0);
- The first example passes in a JavaScript timestamp number as the argument.
- The second example passes in a date string specifying the time zone UTC.
- If the time zone is not specified, the local time zone is used by default. Except ISO 8601 formatted dates use UTC time zone by default.
- If hours, minutes, or seconds are omitted, their values get set to zero.
- The third example sets the time zone to Pacific Standard Time PST.
- The fourth example uses Eastern Standard Time EST.
- The last example uses number arguments for the individual date component values:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
- Note that month is zero based so January is 0, February is 1, March is 2,... December is 11. If month is omitted it defaults to 0 (i.e., January).
- If day is omitted it defaults to 1.
3. Date Static Methods
- Static methods are functions directly attached to a class or constructor function.
Object.getOwnPropertyNames(Date); // returns length, name, prototype, now, parse, UTC
- The now, parse, and UTC methods all return the date timestamp.
Date.parse()
- The Date parse method takes a date string as the argument, parses it, and returns the timestamp.
- ISO 8601 Date Format:
- Date-only format: YYYY-MM-DD
- If no time value is used it defaults to 0s.
- Extended format: YYYY-MM-DDTHH:MM:SSZ
- "T" separates time from the date.
- Uses UTC time zone by default. "Z" stands for zero offset from UTC.
- Extended format with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM
- Extended format with timezone: YYYY-MM-DDTHH:MM:SS-HH:MM
- Timezone is + or - HH:MM offset from UTC.
let timestamp = Date.parse('2025-12-31');
timestamp = Date.parse('2025-12-31T00:00:00Z'); // Z means zero offset from UTC
timestamp = Date.parse('2025-12-30T16:00:00-08:00'); // Offset -8 hours from UTC
- Non-standard date formats:
- You can also pass in non-standard date strings like the below. You can put month then day, or day then month. If the timezone is not specified then the local time zone is used by default.
timestamp = Date.parse('31 Dec, 2025');
timestamp = Date.parse('Dec 31, 2025');
timestamp = Date.parse('Dec 31, 2025, 00:00:00');
timestamp = Date.parse('Dec 31, 2025, 00:00:00 PST');
timestamp = Date.parse('Dec 31, 2025, 00:00:00 -08:00');
Date.UTC()
- The Date.UTC method:
- Takes comma-delimited date and time components as parameters starting with year going all the way down to milliseconds:
Date.UTC(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
- Month is zero indexed, so January is 0, February is 1, ... December is 11.
- If no time is specified it defaults to zeros: 0, 0, 0, 0.
- Uses the UTC time zone.
- Returns the JavaScript timestamp.
- We used these date component numbers earlier with the constructor function when creating a date object.
- Below are some examples.
timestamp = Date.UTC(2025, 11, 31); // returns 1767139200000, which is Dec 31, 2025.
timestamp = Date.UTC(2025, 11, 31, 23, 59, 59); // returns 1767225599000
- The Date now method returns a timestamp of the current datetime.
timestamp = Date.now(); // Returns current timestamp
4. Date instance methods
- Instance methods are functions you apply to an instance of a class or constructor function.
- Instance methods are attached to the object's prototype: Date.prototype.instanceMethod()
- Below are are all the Date.prototype instance properties and methods:
Object.getOwnPropertyNames(Date.prototype); // Returns: constructor, toString, toDateString, toTimeString, toISOString, toUTCString, toGMTString, getDate, setDate, getDay, getFullYear, setFullYear, getHours, setHours, getMilliseconds, setMilliseconds, getMinutes, setMinutes, getMonth, setMonth, getSeconds, setSeconds, getTime, setTime, getTimezoneOffset, getUTCDate, setUTCDate, getUTCDay, getUTCFullYear, setUTCFullYear, getUTCHours, setUTCHours, getUTCMilliseconds, setUTCMilliseconds, getUTCMinutes, setUTCMinutes, getUTCMonth, setUTCMonth, getUTCSeconds, setUTCSeconds, valueOf, getYear, setYear, toJSON, toLocaleString, toLocaleDateString, toLocaleTimeString
Instance methods: Get timestamp or date string
- We will start with methods that get the date value from the date object and return it as a timestamp or string.
Date.prototype.valueOf() and .getTime()
- The valueOf and getTime methods both return the date as a timestamp number.
let dateObj = new Date('2025-09-01 17:30:00 UTC');
timestamp = dateObj.valueOf(); // Returns 1756747800000
timestamp = dateObj.getTime(); // Returns 1756747800000
Date.prototype.toString(), .toDateString(), .toTimeString()
- The toString method returns the date and time as a string using the system's time zone and language settings.
- toDateString returns the date only, and toTimeString returns the time only.
let dateStr = dateObj.toString(); // returns 'Mon Sep 01 2025 10:30:00 GMT-0700 (Pacific Daylight Time)'
dateStr = dateObj.toDateString(); // returns 'Mon Sep 01 2025'
dateStr = dateObj.toTimeString(); // returns '10:30:00 GMT-0700 (Pacific Daylight Time)'
Date.prototype.toUTCString(), toISOString(), toJSON()
- The toUTCString method returns the date as a string using the system's language settings. It uses the UTC time zone.
- The toISOString and toJSON methods return the date as a string using the UTC time zone, and the ISO 8601 extended format.
dateStr = dateObj.toUTCString(); // returns 'Mon, 01 Sep 2025 17:30:00 GMT'
dateStr = dateObj.toISOString(); // returns '2025-09-01T17:30:00.000Z'
dateStr = dateObj.toJSON(); // returns '2025-09-01T17:30:00.000Z'
- You can use the string slice method on toISOString to get just the date portion of the string:
dateStr = dateObj.toISOString().slice(0, 10); // returns '2025-09-01'
5. Instance methods: Get Locale String
Date.prototype.toLocaleDateString(), toLocaleDateString(), toLocaleTimeString()
- You can customize the string format with Locales and options.
- The toLocaleString method is like toString in that it returns the date object as a string in local time and language. The difference is you can pass in a language-region argument to display the date in that language-region's date format.
- In the below example we create a date object, then chain toLocalString with no arguments so it uses your system's default locale to get the time zone and language format.
let dateObj = new Date('2025-09-01 17:30:00');
let dateStr = dateObj.toLocaleString(); // returns '9/1/2025, 5:30:00 PM'
- The next two examples pass in a language-region argument so the date is displayed on those regional formats: English Great Britain displays the differently than English US.
dateStr = dateObj.toLocaleString('en-US'); // returns '9/1/2025, 5:30:00 PM'
dateStr = dateObj.toLocaleString('en-GB'); // returns '01/09/2025, 17:30:00'
- You can pass in an options argument and specify exactly how you want the date string to be formatted.
- 2-digit day and month: For the example below we want to use leading zeros for single digit numbers so we added the '2-digit' option to month, day, hour, and minute.
dateStr = dateObj.toLocaleString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'}); // returns '09/01/2025, 05:30:00 PM'
- 2-digit year, numeric month: In this example we do not want leading zeros in the month or date was we use the 'numeric' option.
dateStr = dateObj.toLocaleString('en-US', {year: '2-digit', month: 'numeric', day: 'numeric', hour: 'numeric', minute: '2-digit'}); // returns '9/1/25, 5:30:00 PM'
- Short text: The next example uses short text for the month name.
dateStr = dateObj.toLocaleString('en-US', {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'}); // returns 'Sep 1, 2025, 5:30 PM'
- Long text, weekday, time zone: The next example uses long text for the month name and includes the weekday and time zone.
dateStr = dateObj.toLocaleString('en-US', {year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', hour: 'numeric', minute: '2-digit', timeZoneName: 'long'}); // returns 'Thursday, September 1, 2025, 5:30 PM Pacific Daylight Time'
Date.prototype.toLocaleDateString()
- Below are date only examples:
dateStr = dateObj.toLocaleDateString(); // (e.g., en-US default) '9/1/2025'
dateStr = dateObj.toLocaleDateString('en-US'); // returns '9/1/2025'
dateStr = dateObj.toLocaleDateString('en-GB'); // returns '01/09/2025'
dateStr = dateObj.toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // returns '09/01/2025'
dateStr = dateObj.toLocaleDateString('en-US', {year: '2-digit', month: 'numeric', day: 'numeric'}); // returns '9/1/25'
dateStr = dateObj.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'}); // returns 'Sep 1, 2025'
dateStr = dateObj.toLocaleDateString('en-US', {year: 'numeric', month: 'long', day: 'numeric', weekday: 'long'}); // returns 'Thursday, September 1, 2025'
Date.prototype.toLocaleTimeString()
- Below are time only examples:
dateStr = dateObj.toLocaleTimeString(); // returns "5:30:00 PM"
dateStr = dateObj.toLocaleTimeString('en-US', {hour: 'numeric', minute: '2-digit'}); // returns "5:30 PM"
dateStr = dateObj.toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit'}); // returns "05:30 PM"
6. Instance methods: Get number values from the date object
Date.prototype.getFullYear(), .getMonth(), etc.
- There are a number of instance methods for getting individual components from the date object. We have getFullYear, getMonth, all the way down to getMilliseconds. The values are returned as numbers. It uses system local time zone by default.
- The getMonth method return value is zero indexed, so January is 0, February is 1, December is 11.
- GetDate returns the day of the month 1 to 31.
- GetDay returns the day of the week. This is also zero indexed so Sunday is 0, Monday 1, Saturday is 6.
- GetTimezoneOffset gets the offset from UTC in minutes.
- The values are returned in local time.
- The below example creates a date object using time zone offset -8 hours from UTC, then uses the get methods to get the various date component values.
let dateObj = new Date('2025-12-31 09:30:00 -8:00');
dateNum = dateObj.getFullYear(); // returns 2025
dateNum = dateObj.getMonth(); // returns 11 which is December.
dateNum = dateObj.getDate(); // returns 31
dateNum = dateObj.getDay(); // returns 6 which is Saturday.
dateNum = dateObj.getHours(); // returns 9
dateNum = dateObj.getMinutes(); // returns 30
dateNum = dateObj.getTimezoneOffset(); // 480; Returns the difference, in minutes, from local time zone to UTC.
Date.prototype.getUTCFullYear(), .getUTCMonth(), etc.
- The below methods get the date components based on the UTC time zone.
dateObj = new Date('2025-12-31 09:30:00 -8:00'); dateNum = dateObj.getUTCFullYear(); // returns 2025
dateNum = dateObj.getUTCMonth(); // returns 11 which is December.
dateNum = dateObj.getUTCDate(); // returns 31
dateNum = dateObj.getUTCDay(); // returns 6 which is Saturday.
dateNum = dateObj.getUTCHours(); // returns 17
dateNum = dateObj.getUTCMinutes(); // returns 30
7. Instance methods: Set Date and Time Values in Date objects
Date.prototype.setFullYear(), .setMonth(), etc.
- Besides getting date component values, you can also set date component values.
- If you have an existing date object you can use the set methods to change the year, month, date, hours, minutes, seconds or milliseconds.
- These methods use the host system's local time.
- Looking at the examples below, the dateObj variable is set with a -8 hours offset from UTC.
- The setFullYear method changes the year. Optionally you can also set the month and day as well, which is what we did. We changed the date to January 1st 2026.
- The setMonth method passes in 1 as the month which is February. We are also passing in an optional date value of 2. The date object is now set to February 2nd 2026.
- SetDate(3) changes the date value to 3. The date is now February 3rd.
- Below that we pass in 0 for the date value, which sets the date to the last day of the previous month. That sets the date back to January 31.
- Then we set the hours to 8. We also pass in optional arguments for minutes and seconds. The date is now January 31st, 2026 8:05 and 30 seconds.
- Then we reset the minutes and optional seconds back to 0.
const dateObj = new Date('2025-12-31 09:30:00 -8:00');
dateObj.setFullYear(2026, 0, 1); // new date: "Jan 1, 2026 9:30 -8:00"
dateObj.setMonth(1, 2); // new date: "Feb 2, 2026 9:30 -8:00"
dateObj.setDate(3); // new date: "Feb 3, 2026 9:30 -8:00"
dateObj.setDate(0); // new date: "Jan 31, 2026 9:30 -8:00". Sets date to the last date of the previous month
dateObj.setHours(8, 5, 30); // new date: "Jan 31, 2026 8:05:30 -8:00"
dateObj.setMinutes(0, 0); // new date: "Jan 31, 2026 8:00:00 -8:00"
Date.prototype.setUTCFullYear(), .setUTCMonth(), etc.
- The below set of examples sets the date components using the UTC time zone.
dateObj = new Date('2025-12-31 09:30:00 UTC');
dateObj.setUTCFullYear(2026, 0, 1); // new date: Jan 1, 2026 9:30 UTC.
dateObj.setUTCMonth(1, 2); // new date: Feb 2, 2026 9:30 UTC
dateObj.setUTCDate(3); // new date: Feb 3, 2026 9:30 UTC
dateObj.setUTCDate(0); // new date: Jan 31, 2026 8:05:30 UTC
dateObj.setUTCHours(8, 5, 30); // new date: Jan 31, 2026 0:05:30 UTC
dateObj.setUTCMinutes(0, 0); // new date: Jan 31, 2026 0:00:00 UTC
- And that concludes this tutorial on JavaScript Dates.
Conclusion
The topics in this tutorial correspond with the JavaScript CheatSheet Dates category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.