Table of Contents
- Understanding Timestamps
- Manipulating Timestamps
- Formatting Timestamps
- Dealing with Timezones
Creating a Timestamp
Date object to work with dates and times. To create a new timestamp, you instantiate a new
This code snippet creates a new
Date object representing the current date and time and then uses the
getTime() method to get the timestamp.
Converting a Date String to a Timestamp
To convert a date string to a timestamp, you pass the string to the
Date constructor and then use
Once you have a timestamp, you can manipulate it - for instance, to add or subtract time.
Adding Time to a Timestamp
To add time to a timestamp, add the number of milliseconds:
Subtracting Time from a Timestamp
Similarly, you can subtract time:
Date object can help with that.
Converting a Timestamp to a Readable Date String
To convert a timestamp to a human-readable date, create a new
Date object and then use formatting methods:
Dealing with Timezones
Date object works in the local time of the user's browser, but you can also work with UTC (Coordinated Universal Time).
Converting to UTC
To convert a local time to UTC, you can use
Date methods like
Date object is a powerful tool. Still, for more complex operations, you might want to consider libraries like Day.js or Date-fns, which offer more features and can simplify some of the intricacies of date and time manipulation.
Happy coding! 🚀