Chapter 4. Dates
JavaScript has surprisingly capable date features, which are wrapped in the somewhat old-fashioned Date object. As you’ll see, the Date object has quirks and hidden traps—like the way it counts months starting at 0 and parses year information differently depending on the locale settings of the current computer. But once you learn to navigate these stumbling blocks, you’ll be able to accomplish a number of common, useful operations, like counting the days between two dates, formatting dates for display, and timing events.
Getting the Current Date and Time
Problem
You need to get the current date or time.
Solution
JavaScript includes a Date object that provides good support for manipulating date information (and more modest support for performing date calculations). When you create a new Date object, it is automatically populated with the current day and time, down to the nearest millisecond:
consttoday=newDate();
Now it’s simply a matter of extracting the information you want from your Date object. The Date object has a long list of methods that can help you in this task. Table 4-1 lists the most important methods. Notice that the counting used by different methods isn’t always consistent. Months and weekdays are numbered starting at 0, while days are numbered starting at 1.
| Method | Gets | Possible values |
|---|---|---|
|
The year |
A four-digit number like 2021 |
|
The month number ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access