JavaScript Dates and Time
# JavaScript Dates and Time
Every application deals with time. When was this post published? Has the user's session expired? What is today's date?
In this chapter, we will learn how to capture, format, and manipulate dates and times using JavaScript's built-in Date object.
1. Introduction
Unlike Strings or Numbers, JavaScript does not have a "Date" primitive data type. Instead, you must create a new instance of the Date object to work with dates and times.
By default, JavaScript will use the browser's time zone and display the date as a full text string. It stores dates under the hood as the number of milliseconds that have passed since January 1, 1970 (known as the Unix Epoch).
2. Learning Objectives
By the end of this chapter, you will be able to:
- Create a Date object representing the current time.
- Create a Date object for a specific past or future date.
- Use "Get" methods to extract the year, month, day, hours, and minutes.
- Understand the zero-index trap of JavaScript months.
- Format dates into readable strings.
- Build a working real-time Digital Clock mini-project.
3. Creating a Date Object
You create a date object using the new Date() constructor. There are 4 ways to initialize a new date:
-
1.
new Date()(Current date and time)
-
2.
new Date(year, month, day, hours, minutes, seconds, milliseconds)(Specific date)
-
3.
new Date(milliseconds)(Milliseconds since Jan 1, 1970)
-
4.
new Date(date string)(Create from a string)
4. The JavaScript Month Trap
CRITICAL RULE: In JavaScript, Months are zero-indexed (just like arrays).
-
January is
0.
-
February is
1.
-
December is
11.
Days of the month (getDate()) are normal (1-31), but Days of the week (getDay()) are also zero-indexed (Sunday = 0, Monday = 1, Saturday = 6).
---
5. Real-world Examples & Code Snippets
Example 1: Creating Specific Dates
Example 2: Creating Dates from Strings
If you omit the specific arguments and just pass a string, JavaScript will try its best to parse it. It is usually best to use the ISO standard format: YYYY-MM-DD.
Example 3: "Get" Methods (Extracting Data)
Once you have a Date object, you can pull specific pieces of information out of it.
Example 4: Getting the Timestamp (Milliseconds)
The getTime() method returns the number of milliseconds since Jan 1, 1970. This is incredibly useful for measuring how long a task took to execute, or comparing which of two dates is older.
Example 5: "Set" Methods (Modifying Data)
You can change a Date object after you create it using Set methods.
Example 6: Formatting Dates nicely
The default output of new Date() is ugly for users. You can format it beautifully.
Example 7: Creating an Array of Month Names
Because getMonth() returns a number (0-11), developers often use an array to get the text name of the month.
Example 8: Comparing Dates
Because dates are stored as milliseconds under the hood, you can use standard comparison operators (> , <) to compare them.
Example 9: Calculating Time Difference
To find out how many days exist between two dates, you subtract them to get the difference in milliseconds, then do some math.
Example 10: Padding Single Digits
When making clocks, getMinutes() might return 5. A clock showing 10:5 looks broken; it should be 10:05.
---
6. Common Mistakes for Beginners
-
1.
The Month Trap: Writing
new Date(2024, 1, 1)and expecting January 1st. It will actually be February 1st because index 1 is February!
-
2.
Confusing
getDay()withgetDate():getDate()gives you the day of the month (1-31).getDay()gives you the day of the week (0-6).
-
3.
Assuming timezone consistency: If you fetch a date string from a server in London and open it in a browser in New York,
new Date()will automatically convert it to New York time. This is a common source of bugs in enterprise apps.
7. Best Practices
-
Always use
toLocaleDateString()andtoLocaleTimeString()to format dates for users, as it automatically respects the user's computer locale settings (e.g., MM/DD vs DD/MM).
- For very complex date manipulation (timezones, recurring calendar events), professional developers rarely use the native Date object. They use libraries like date-fns or Moment.js.
8. Mini Project: Real-time Digital Clock
Let's build a clock that updates every second on the screen. (We will use a timer function we officially cover in Chapter 27, but it's simple enough to use here!)
HTML:
clock.js:
9. Exercises
-
1.
Create a variable
nowholding a new Date object.
-
2.
Console log the current full year using a method from the
nowobject.
- 3. Console log the current month. Remember the output is a zero-indexed number!
10. MCQs (Multiple Choice Questions)
Q1: What will new Date(2024, 0, 1) create?
A) February 1, 2024
B) January 1, 2024
C) Error
D) December 1, 2024
*Answer: B (Because Month 0 is January)*
Q2: Which method returns the day of the week (0-6)?
A) getDate()
B) getDay()
C) getDayOfWeek()
D) getTime()
*Answer: B*
Q3: How are dates fundamentally tracked behind the scenes in JavaScript? A) As a String in ISO format B) As an Object with 6 properties C) As Milliseconds since Jan 1, 1970 D) As a 64-bit Hash *Answer: C*
11. Interview Questions
Q: Why do developers often convert Dates to Milliseconds (getTime()) before comparing them?
*A: Comparing Date objects directly using == or === will return false even if they represent the exact same millisecond in time, because they are comparing Object references in memory, not the values. Converting them to primitive numbers (milliseconds) allows for strict, accurate mathematical comparison.*
12. FAQs
Q: Can I get the user's timezone?
*A: Yes! You can use Intl.DateTimeFormat().resolvedOptions().timeZone to get a string like "America/New_York".*
13. Summary
-
Create a date with
new Date().
- Months and Days of the Week are zero-indexed!
-
Use
getFullYear(),getMonth(),getDate(),getHours(),getMinutes()to extract data.
-
Use
setFullYear(),setMonth(), etc., to modify data.
-
getTime()returns milliseconds since Jan 1, 1970.
-
toLocaleDateString()formats dates perfectly for UI display.