Timestamp conversions are a common task when working with date and time in Node.js. Fortunately, Node.js provides several libraries for this purpose, and one of the most popular is dayjs.
dayjs is a lightweight and fast library for parsing, validating, manipulating, and formatting dates and times. It is similar to the well-known moment.js library, but with a smaller bundle size and faster performance.
Here are some examples of how to use dayjs for timestamp conversions in Node.js:
Convert a timestamp to a formatted date and time string:
In this example, dayjs(timestamp) creates a dayjs object from the given timestamp, and format('YYYY-MM-DD HH:mm:ss') formats it into a string that represents the date and time in the desired format.
In this example, dayjs(timestamp).tz('America/New_York') converts the timestamp to the America/New_York time zone and returns a dayjs object in that time zone. valueOf() then returns the timestamp in milliseconds.
These are just a few examples of how dayjs can be used for timestamp conversions in Node.js. dayjs provides many more features for manipulating and formatting dates and times, and it's worth exploring its documentation to learn more.
Converting a Unix Timestamp to a Date String:
The Unix timestamp represents the number of milliseconds since January 1, 1970, UTC. To convert a Unix timestamp to a date string, we can use the dayjs library's format() method. Here's an example:
In this example, we create a dayjs object from the date string and then use the tz() method to convert it to the America/New_York timezone. Finally, we use the format() method to format the date in the desired format.
Converting a Date Object to a Date String:
To convert a Date object to a date string, we can use the dayjs library's format() method. Here's an example: