Convert date time to date javascript

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:

const date = new Date(); console.log(date);
Code language: JavaScript (javascript)

The Date constructor.

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.

const date = Date.now(); console.log(date);
Code language: JavaScript (javascript)

The Date constructor without the new keyword.

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.

Читайте также:  Animate css при скролле

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.

const date = new Date(1666632563517); console.log(date);
Code language: JavaScript (javascript)

Convert timestamp to a valid date object.

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.

const date = new Date(1666632563517); console.log(date.toDateString());
Code language: JavaScript (javascript)

Date.toDateString() method to format the date.

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.

const date = new Date(1666632563517); console.log(date.toLocaleDateString('en-US'));
Code language: JavaScript (javascript)

Date.toLocaleDateString() method to format the date.

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.

const date = new Date(1666632563517); console.log(date.toLocaleString());
Code language: JavaScript (javascript)

Date.toLocaleString() method to format the date.

Other date object methods

To format the date, we may use methods on the date object such as getDate() , `getMonth()`, and getFullYear() .

const date = new Date(1666632563517); console.log(date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear());
Code language: JavaScript (javascript)

Class method to format the date.

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:

npm install moment
Code language: Bash (bash)

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.

const date = moment.unix("1666632563"); console.log(date);
Code language: JavaScript (javascript)

Convert a timestamp to a valid date object using moment.js.

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.

const date = moment.unix("1666632563").format("DD/MM/YYYY"); console.log(date);
Code language: JavaScript (javascript)

Format the date using moment.js.

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.

Источник

How to Convert Timestamp to Date Format in JavaScript

In JavaScript, there are situations where there is a need to convert the random or incorrect date and time value which is independent of any time zone or calendar. For instance, when it is required to get the value of each attribute in the date format. In such cases, JavaScript can help you to encode the unformatted timestamp value in the proper date and time format.

This manual will guide you related to converting Timestamp into date format in JavaScript.

How to Convert Timestamp Value in Date Format in JavaScript?

To convert timestamp value in date format in JavaScript, the following methods can be applied:

Go through the discussed methods one by one!

Method 1: Convert Timestamp into Date Format in JavaScript Using New Date() Constructor

The new Date() constructor creates a new object named date with the current date and time. This method can be applied to create a Date object referring to the declared timestamp value and displaying the converted date format.

The below example will demonstrate the stated concept.

First, declare a variable named “timeStamp” and store a specific value in it:

Next, apply the “Date()” constructor to create a new date object and use the timeStamp value as its argument:

Finally, log the converted date format value on the console:

The output of the above implementation will result as follows:

Method 2: Convert Timestamp to Date Format in JavaScript Using getHours(), getMinutes() and toDateString() Methods

Firstly, assign a particular timestamp value and store it in a variable named timeStamp:

Next, apply the “Date()” constructor to create a new date object with the timeStamp value as its argument as discussed in the previous method:

After that, apply the getHours() and getMinutes() methods to get the hours and minutes with respect to the assigned timeStamp value. Also, apply the toDateString() method to get the corresponding date as well:

Finally, display the resultant date format on the console:

Method 3: Convert Timestamp to Date Format in JavaScript Using Date Class Methods

The Date class provides various methods to represent the declared timestamp into the date format. This method can be implemented to create a new date object and display the corresponding date format by applying the methods for fetching each of its attributes separately.

Look at the following example.

Repeat the steps discussed in the above methods for initializing a timestamp value and creating a new date object as follows:

Now, apply the getDate() method for getting the day of the month, getMonth() for getting the month, getFullYear() for getting the value of the full year. Also, apply the getHours(), getMinutes(), and getSeconds() for getting the corresponding time against the provided time stamp.

Lastly, add all the attributes to get the date format sequentially:

console. log ( «Date: » + dateFormat. getDate ( ) +
«/» + ( dateFormat. getMonth ( ) + 1 ) +
«/» + dateFormat. getFullYear ( ) +
» » + dateFormat. getHours ( ) +
«:» + dateFormat. getMinutes ( ) +
«:» + dateFormat. getSeconds ( ) ) ;

We have compiled different methods to convert timestamp to date format in JavaScript.

Conclusion

To convert timestamp to date format in JavaScript, apply the “New Date()” Constructor method to create a new date object and display the current date and time. Also, apply the getHours(), getMinutes(), and toDateString() methods to compile the time and date and display them. Moreover, the Date Class methods can also be utilized for the same purpose. This article guided related to converting timestamp to date format in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Оцените статью