Dates in JavaScript - Understanding the basics
Introduction
Dates are an essential part of any programming language, and JavaScript is no exception. The Date
object was introduced in JavaScript in the first version of the language, ECMAScript 1, in 1997. JavaScript's Date
object provides a simple, yet powerful, way to work with dates and times in various ways.
We'll cover the basics of working with dates in JavaScript, explore some of the more advanced features, and delve into some real-world examples of how dates are used in modern day web apps.
Creating Dates
The simplest way to create a date in JavaScript is by using the new Date()
constructor. This creates a new date object with the current date and time. Here's an example:
let currentDate = new Date();
console.log(currentDate); // Mon Jan 16 2022 12:00:00 GMT+0000 (UTC)
JavaScript will use the browser's time zone and will display the date and time in that format. The format can go up to milliseconds. Also, JavaScript counts months from 0 to 11.
You can also create a date object with a specific date and time by passing a string or a set of parameters to the new Date()
constructor. Here are a few examples:
let specificDate = new Date("January 1, 2022");
console.log(specificDate); // Mon Jan 01 2022 00:00:00 GMT+0000 (UTC)
let specificDateWithParams = new Date(2022, 0, 1); // month 0 is January
console.log(specificDateWithParams); // Mon Jan 01 2022 00:00:00 GMT+0000 (UTC)
Retrieving Date Information
Once you have a date object, you can use various methods to retrieve information about the date, such as the year, month, and day. Here are a few examples:
let date = new Date();
console.log(date.getFullYear()); // 2022
console.log(date.getMonth()); // 0 (January)
console.log(date.getDate()); // 16
You can also use the getDay()
method to get the day of the week (0 for Sunday, 1 for Monday, etc.) and the getHours()
, getMinutes()
, and getSeconds()
methods to get the time.
Formatting Dates
JavaScript provides a built-in toString()
method that allows you to format a date as a string. However, this method returns a string in the format "Mon Jan 16 2022 12:00:00 GMT+0000 (UTC)", which may not be very user-friendly.
To format a date in a more human-readable format, you can use the toLocaleDateString()
and toLocaleTimeString()
methods. Here's an example:
let date = new Date();
console.log(date.toLocaleDateString()); // "1/16/2022"
console.log(date.toLocaleTimeString()); // "12:00:00 PM"
You can also use the toUTCString()
method to format a date in UTC format, and the toISOString()
method to format a date as an ISO-8601 string, which is a standardized format that can be used across different systems and languages. Here's an example:
let date = new Date();
console.log(date.toISOString()); // "2022-01-16T12:00:00.000Z"
Manipulating Dates
JavaScript provides several methods that allow you to manipulate dates, such as adding or subtracting time. Here are a few examples:
let date = new Date();
// Add one day
date.setDate(date.getDate() + 1);
console.log(date); // Tue Jan 17 2022 12:00:00 GMT+0000 (UTC)
// Subtract one month
date.setMonth(date.getMonth() - 1);
console.log(date); // Tue Dec 17 2022 12:00:00 GMT+0000 (UTC)
You can also use the setFullYear()
, setMonth()
, setDate()
, setHours()
, setMinutes()
, and setSeconds()
methods to set the respective values of a date.
Built-in Date Methods and Properties
JavaScript's built-in Date object provides a wide range of methods and properties for working with dates. Here is a list of some of the most commonly used methods and properties:
Note: The syntax for calling the methods and properties is Date.
+ the method/property name
Date Methods
Method | Description |
---|---|
now() | Returns the current time in milliseconds since January 1, 1970, 00:00:00 UTC |
parse(dateString) | Parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC |
UTC(year, month, day, hours, minutes, seconds, milliseconds) | Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC for a specified date and time according to universal time |
getTime() | Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, for a date object |
setTime(milliseconds) | Sets a date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC |
getDate() | Returns the day of the month of a date as a number (1-31) |
setDate(day) | Sets the day of the month of a date object |
getDay() | Returns the day of the week of a date as a number (0-6) |
getMonth() | Returns the month of a date as a number (0-11) |
setMonth(month, day) | Sets the month (and optionally day) of a date object |
getFullYear() | Returns the year of a date as a four-digit number |
setFullYear(year, month, day) | Sets the full year (and optionally month and day) of a date object |
toUTCString() | Returns a string representation of the date in UTC time |
toISOString() | Returns a string representation of the date in ISO format |
toDateString() | Returns the date as a string in the format "Weekday Month Date Year" |
toLocaleDateString() | Returns a string representation of the date, in the format appropriate for the host environment's current locale |
toLocaleString() | Returns a string representation of the date, in the format appropriate for the host environment's current locale |
toLocaleTimeString() | Returns a string representation of the time, in the format appropriate for the host environment's current locale |
toString() | Returns a string representation of the date |
toTimeString() | Returns the time as a string in the format "Hours:Minutes:Seconds GMT+offset" |
valueOf() | Returns the primitive value of a date object |
Date Properties
Property | Description |
---|---|
getUTCDate() | Returns the day of the month of a date according to universal time (0-31) |
getUTCDay() | Returns the day of the week of a date according to universal time (0-6) |
getUTCFullYear() | Returns the year of a date according to universal time |
getUTCHours() | Returns the hour of a date according to universal time (0-23) |
getUTCMilliseconds() | Returns the milliseconds of a date according to universal time (0-999) |
getUTCMinutes() | Returns the minutes of a date according to universal time (0-59) |
getUTCMonth() | Returns the month of a date according to universal time (0-11) |
getUTCSeconds() | Returns the seconds of a date according to universal time (0-59) |
Please note that these are just some commonly used methods and properties and there are other methods and properties also available in JavaScript.
Real-World Examples
Dates are used in many different ways in web development and web apps. Some common use cases include:
Displaying the current date and time on a website
Calculating the difference between two dates
Formatting dates for display to users in different timezones and locales
Parsing dates from user input
Storing and retrieving dates in a database
Using Libraries
While JavaScript's built-in Date
object provides a wide range of options for working with dates, there are also many third-party libraries available that can make working with dates even easier. One such library is date-fns
, which provides a more comprehensive set of date manipulation functions that that might not be available in JavaScript's built-in Date object.
Here's an example of using date-fns to format a date:
import { format } from 'date-fns'
let date = new Date()
let formattedDate = format(date, 'MM/dd/yyyy')
console.log(formattedDate) // "01/16/2022"
Additionally, date-fns
has a variety of other useful functions, such as addDays
, subtractDays
, isBefore
, isAfter
, etc. These functions allow you to easily manipulate and compare dates in a more readable and maintainable way.
Using a library can make it easier to handle some of the more complex aspects of working with dates, such as timezones, localization, and parsing.
Conclusion
We've covered the basics and intricacies of working with dates in JavaScript. Here's a quick rundown:
Understanding the basics of creating and manipulating dates with the built-in Date object in JavaScript.
Formatting dates to different human-readable formats.
Comparing dates to check if one date is before or after another.
Real-world examples of using dates in web apps.
The benefits of using libraries like date-fns for date manipulation and localization.