Date & Time
Master JavaScript dates! Learn to create, format, and manipulate dates and times.
Master JavaScript dates! Learn to create, format, and manipulate dates and times. This hands-on tutorial focuses on practical implementation of date & time concepts.
Date & Time
Handling dates and times is a common task in programming. JavaScript provides the built-in Date object to help us work with time.
1. Creating Dates π
What is it?
A Date object represents a single moment in time.
How it works: You can create a date in 4 ways:
2. Getting Date Info π
Once you have a Date object, you can extract specific parts (year, month, day, etc.).
Crucial:
getMonth()returns 0-11 (Jan is 0).getDay()returns 0-6 (Sunday is 0).getDate()returns 1-31 (Day of the month).
3. Formatting Dates π
Displaying dates to users requires formatting.
4. Date Arithmetic ββ
You can modify dates or calculate the difference between them.
Tip: When you subtract two dates, you get the difference in milliseconds.
5. Timestamps β±οΈ
A timestamp is a single number representing milliseconds since January 1, 1970 (Unix Epoch). It's great for storing dates in databases.
Practical Example: "Time Ago" Function β³
AI Mentor
Confused about "JavaScript Date object, timestamps, date formatting, and date arithmetic"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4What does new Date(2024, 0, 1) represent?
Key Takeaways
β
Months are 0-indexed (Jan = 0).
β
Date.now() gives current timestamp.
β
getTime() converts Date to timestamp.
β
toISOString() is standard for APIs.
β
Subtract dates to get time difference.
What's Next?
Now let's learn how to handle errors gracefully with Error Handling!
Keep coding! π