- Convert a Unix Timestamp to a Date in Vanilla JavaScript
- Table of Contents
- Convert the Unix Timestamp to Milliseconds
- Create a Date Object Using new Date()
- Create Human-Friendly Date Strings With .toLocaleString()
- How to convert timestamp to date in JavaScript?
- Converting timestamps to date formats in JavaScript
- Formatting the date
- Date.toDateString()
- Date.toLocaleDateString()
- Date.toLocaleString()
- Other date object methods
- Converting timestamps to date formats in JavaScript using Moment.js
- Conclusion
- Sharing is caring
- Html timestamp to date
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Convert a Unix Timestamp to a Date in Vanilla JavaScript
How do you convert a Unix timestamp value into a human-readable date using vanilla JavaScript?
You can convert the Unix timestamp to a date string by following these three steps:
- Convert the unix timestamp into milliseconds by multiplying it by 1000 .
- Use the newly created milliseconds value to create a date object with the new Date() constructor method.
- Use the .toLocaleString() function to convert the date object into human-friendly date strings.
In this article, we’ll walk you through each of those steps.
Table of Contents
Convert the Unix Timestamp to Milliseconds
Since the new Date() function needs to be supplied with a milliseconds value, we need to first convert our given Unix timestamp to milliseconds. We can do this by simply multiplying the Unix timestamp by 1000 .
Unix time is the number of seconds that have elapsed since the Unix epoch, which is the time 00:00:00 UTC on 1 January 1970 . It’s most commonly used to create a running total of seconds when interacting with computers.
Therefore, a Unix timestamp is simply the number of seconds between a specific date and the original Unix Epoch date.
Measuring time using Unix timestamps is particularly useful because it is the same for everyone around the globe at all times since they don’t observe timezones. This can be very useful for dealing with dated information on both the server and client-side of applications.
So, let’s write some code to convert a Unix timestamp to milliseconds:
const unixTimestamp = 1575909015 const milliseconds = unixTimestamp * 1000 // 1575909015000
Feel free to substitute your own Unix timestamp in the code above.
In the next section, we’ll put to use that milliseconds value we just created.
Create a Date Object Using new Date()
Now that we have a milliseconds value, we can create a new Date() object.
The Date object instance we create will represent a single moment in time and will hold data on the year, month, day, hour, minute, and second for that moment in time.
Let’s add on to the code we already wrote in the last section. To create the Date object, make your code look like this:
const unixTimestamp = 1575909015 const milliseconds = 1575909015 * 1000 // 1575909015000 const dateObject = new Date(milliseconds)
We use the new Date() constructor and pass to it the milliseconds variable we created in the last section.
As a result, we’re left with a newly created dateObject variable that represents the Date object instance.
We’ll use this in the next section.
Create Human-Friendly Date Strings With .toLocaleString()
Now that we have a Date object to work with, we can start creating some human-friendly date strings.
Using the .toLocaleString() function is one really easy way to do this. The function can be called on a data object and will return a string with a language sensitive representation of the date portion of the given date object.
Here’s what a simple code example looks like (adding on to the code we have written in the past sections):
const unixTimestamp = 1575909015 const milliseconds = 1575909015 * 1000 // 1575909015000 const dateObject = new Date(milliseconds) const humanDateFormat = dateObject.toLocaleString() //2019-12-9 10:30:15
As you can see, we created a human-friendly date string by calling the .toLocaleString() on the dateObject we created in the last section.
Here are some examples of how you can use the .toLocaleString() to return strings of specific components of the date by passing different arguments to the .toLocaleString() function:
const unixTimestamp = 1575909015 const milliseconds = 1575909015 * 1000 // 1575909015000 const dateObject = new Date(milliseconds) const humanDateFormat = dateObject.toLocaleString() //2019-12-9 10:30:15 dateObject.toLocaleString("en-US", ) // Monday dateObject.toLocaleString("en-US", ) // December dateObject.toLocaleString("en-US", ) // 9 dateObject.toLocaleString("en-US", ) // 2019 dateObject.toLocaleString("en-US", ) // 10 AM dateObject.toLocaleString("en-US", ) // 30 dateObject.toLocaleString("en-US", ) // 15 dateObject.toLocaleString("en-US", ) // 12/9/2019, 10:30:15 AM CST
The .toLocaleString takes a locales string parameter that alters results based on language and geography. In the example above, we used the «en-US» locale tag. You can learn more about other values you can use instead here.
We also passed an object with some options in it as well. If you want to learn more, there’s some good information about those here.
How to convert timestamp to date in JavaScript?
If you have worked with backend servers and databases, you might know that mainly these backend servers store the date (and time) as a string containing a timestamp. The front-end application may need to display these dates in a proper format. But since these dates are in the form of a timestamp, we must know how to convert these timestamps into an appropriate format of date, taking into account the user’s timezone. Doing this is pretty straightforward with JavaScript. Alternatively, we may use some popular open-source libraries to make things even more straightforward.
This article will look at several techniques for converting a string containing the timestamp information into a proper date format. As a bonus, we’ll go through a couple of popular open-source libraries that we primarily use for this purpose.
Converting timestamps to date formats in JavaScript
JavaScript provides an API for working with dates and times, which we can access via the Date constructor. It produces a date object with numerous parsing and formatting methods. Using the Date constructor, we can build a date object as follows:
Code language: JavaScript (javascript)const date = new Date(); console.log(date);
Alternatively, we may also use the Date.now() function instead. It produces a timestamp value reflecting the amount of milliseconds since the 1st of January, 1970.
Code language: JavaScript (javascript)const date = Date.now(); console.log(date);
We may optionally pass a few options to the Date constructor when building a date object. These parameters can be a timestamp, a date string, a date object, or particular date and time components such as day, month, year, and so on.
We may optionally supply a timestamp to the Date constructor when producing the current date. As a result, a string comprising the date, time, and timezone is returned.
Code language: JavaScript (javascript)const date = new Date(1666632563517); console.log(date);
Formatting the date
Using the date object’s methods, we can format the produced date. Let’s have a look at some of the strategies accessible one by one.
Date.toDateString()
Date.toDateString() returns the date in a compressed format. To use this approach, we will generate the proper date using the timestamp supplied and then convert the date to a simple format.
Code language: JavaScript (javascript)const date = new Date(1666632563517); console.log(date.toDateString());
Date.toLocaleDateString()
We obtain the date in the format of the user’s timezone by using the Date.toLocaleDateString() function. We may also pass extra arguments to style the date according to language requirements.
Code language: JavaScript (javascript)const date = new Date(1666632563517); console.log(date.toLocaleDateString('en-US'));
Date.toLocaleString()
Date.toLocaleString() functions in the same way as Date.toLocaleDateString() does. The key distinction between the two is that, in contrast to the Date.toLocaleDateString() function, which creates the date, the Date.toLocaleString() method also generates the time.
Code language: JavaScript (javascript)const date = new Date(1666632563517); console.log(date.toLocaleString());
Other date object methods
To format the date, we may use methods on the date object such as getDate() , `getMonth()`, and getFullYear() .
Code language: JavaScript (javascript)const date = new Date(1666632563517); console.log(date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear());
Converting timestamps to date formats in JavaScript using Moment.js
Moment.js is a JavaScript library that got released in 2011. It is used primarily for working with dates in JavaScript. It contains various methods for parsing and validating dates in JavaScript. Also, it has a very developer-friendly API for working with dates.
In JavaScript, we can use this library to convert and format the timestamp value into a valid date format. We will utilize the moment.unix() method to do this. It takes a timestamp as an argument and outputs a date object.
We may install it using the NPM package manager with the following command:
Code language: Bash (bash)npm install moment
Alternatively, we can also use a CDN by including a tag in our HTML document.
We write the following code to convert the timestamp value to a date object.
Code language: JavaScript (javascript)const date = moment.unix("1666632563"); console.log(date);
We may format the generated date by chaining the format() method. It accepts a string, containing the date format, as an argument. We will use the following code to format the created date.
Code language: JavaScript (javascript)const date = moment.unix("1666632563").format("DD/MM/YYYY"); console.log(date);
Conclusion
In this article, we looked at several methods for converting timestamps into the appropriate date and time format. Additionally, we looked at a couple of popular open-source libraries that we primarily use for this purpose.
Thank you so much for reading ?
Codedamn is the best place to become a proficient developer. Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.
Unlimited access to all platform courses
100’s of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Varun Tiwari wrote? Thank them for their work by sharing it on social media.
Html timestamp to date
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter