Javascript timestamp to date format

Timestamp to DateTime in JavaScript

In this post, we are going to learn how to convert Timestamp to DateTime in JavaScript with example. First, we will learn how to get Unix timestamp in Javascript and convert this to datetime and different timezone.

How to Get Unix timestamp in Javascript

To convert a UNIX timestamp to date, the first step is to get the current timestamp in Javascript or even you can use a hard code value

2 ways to get Unix timestamp in Javascript

  • By using the getTime()
  • Get timestamp from a given date: we have to convert it into milliseconds by multiplying 1000.

Program to get unix Timestamp

const current_timestamp = new Date().getTime() console.log(current_timestamp); //timestamp from a date function datetoTimestamp(strDate) < var date = Date.parse(strDate); return date/1000; >timestamp = datetoTimestamp('10/19/2021, 4:21:54 ') timestamp_to_milsec = timestamp*1000; console.log('millsecond:',timestamp_to_milsec);
1634659545467 millsecond: 1634617314000
  • getDate():Use to get day of calendar month 1 to 31.
  • getMonth(): Use to get month number 0 to 11.
  • getFullYear(): Use to get year in 4-digits format.
  • getHours():Use to get the hour in 24-hour format.
  • getMinutes():Use to get the minutes 0 to 59.
  • getSeconds() : Use to get seconds 0 to 59.
Читайте также:  Демонстрационная страница HTML

JavaScript Program to Unix timestamp to DateTime

In this example, we have used getime() method to get the UNIX timestamp in milliseconds and create an object of the date class and use its method to get datetime.

By using the hard code value instead of finding the current timestamp.

//get unixtimestamp usng gettime() method const current_timestamp = new Date().getTime() console.log(current_timestamp); var date = new Date(current_timestamp); console.log("Full date: "+date.getDate()+"/"+(date.getMonth()+1)+ "/"+date.getFullYear()+" "+date.getHours()+ ":"+date.getMinutes()+":"+date.getSeconds()); //by using hard code value of timestamp var millsecond = 1634660514*1000; var date = new Date(millsecond); console.log("Full date: "+date.getDate()+"/"+(date.getMonth()+1)+ "/"+date.getFullYear()+" "+date.getHours()+ ":"+date.getMinutes()+":"+date.getSeconds());
Full date: 19/10/2021 16:17:40 Full date: 19/10/2021 16:21:54

2. toDateString() to Convert timestamp to date in JavaScript

In this example, we are using the todateString() method to get the date from UNIX epoch time/unixtimestamp.

JS Program to convert unix timestamp to date

var millsecond = 1634617314*1000; var date = new Date(millsecond).toDateString(); console.log(date)

3. Convert timestamp to different timezone

To convert Unix timestamp tolocalstring() function is used to convert a date object to a string based on passed argument value convert date to a different timezone.

Synatx

tolocalstring(locales,options)

Parameters

  • Locales: The locales is an array of locale strings that is language-specific format based on national geography. In the below example, we have used “en-US”.
  • options: It conatins more property that represent comparsion options.

JS Program unix timestamp to different timezone

We can change the locales as per need from the below locales tables.

//get datetime var millsecond = 1634660514*1000; var datetime = new Date(millsecond).toLocaleString("en-US"); console.log('datetime=,datetime) //get date only var date = new Date(millsecond).toLocaleDateString("en-US"); console.log('date=',date) //get time only var time = new Date(millsecond).toLocaleTimeString("en-US"); console.log('time=',time) //by using the second options parameters var datetime = new Date(millsecond); var datestr = datetime.toLocaleString(); console.log(datestr) console.log(datetime.toLocaleString("en-US", )) console.log(datetime.toLocaleString("en-US", )) console.log(datetime.toLocaleString("en-US", )) console.log(datetime.toLocaleString("en-US", ))
dateTime = 10/19/2021, 4:21:54 PM date = 10/19/2021 Time = 4:21:54 PM 10/19/2021, 4:21:54 AM Tuesday, October 19, 2021 Tuesday 10/19/2021, 4:21:54 AM Coordinated Universal Time 04 AM

Tables of locals for different timezone

Summary

In this post, we have learned how to convert Timestamp to DateTime in JavaScript.how to get Timestamp. How to convert timestamps at different timezone.

Читайте также:  Java streams map to string

Источник

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.

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.

Источник

Convert Unix Timestamp to Date in JavaScript

Convert Unix Timestamp to Date in JavaScript

This tutorial will explain how we can convert the Unix timestamp to date in JavaScript. Unix timestamp is the time elapsed since the 1, Jan 1970 00:00:00 UTC, represented in seconds.

The JavaScript Date object contains the representation for the time elapsed since the 1, Jan 1970 00:00:00 UTC in milliseconds.

Convert Unix Timestamp to Date in JavaScript

When we create a new object from the Date() class using new Date() , it returns the time in milliseconds when it is created. If we need to get an object from the Date class at a specific point of time, we can pass the epoch timestamp to that class’s constructor.

var timestamp = 1607110465663 var date = new Date(timestamp); console.log(date.getTime()) console.log(date) 
1607110465663 2020-12-04T19:34:25.663Z 

The Date class provides many methods to represent the Date in the preferred format like:

  1. getDate() returns the day of the calendar month 1 to 31 at that time.
  2. getMonth() returns the month number 0 to 11 at that time.
  3. getFullYear() returns the year in 4-digits format.
  4. getHours() returns the exact hour in 24-hour format for that time.
  5. getMinutes() returns the exact minutes 0 to 59 at that time.
  6. getSeconds() returns the exact seconds 0 to 59 at that time.
var timestamp = 1607110465663 var date = new Date(timestamp);  console.log("Date: "+date.getDate()+  "/"+(date.getMonth()+1)+  "/"+date.getFullYear()+  " "+date.getHours()+  ":"+date.getMinutes()+  ":"+date.getSeconds()); 

Since the JavaScript Date timestamp is in the unit of millisecond while the Unix timestamp is in the unit of second, we can multiply 1000 to convert the Unix timestamp to JavaScript timestamp. If the Unix timestamp is 1607110465 , then the JavaScript timestamp is 1607110465000 .

The following example demonstrates how we can convert the Unix timestamp to JavaScript Date timestamp.

var unixTimestamp = 62678980 var date = new Date(unixTimestamp*1000); console.log("Unix Timestamp:",unixTimestamp) console.log("Date Timestamp:",date.getTime()) console.log(date) console.log("Date: "+date.getDate()+  "/"+(date.getMonth()+1)+  "/"+date.getFullYear()+  " "+date.getHours()+  ":"+date.getMinutes()+  ":"+date.getSeconds()); 
Unix Timestamp: 62678980 Date Timestamp: 62678980000 Mon Dec 27 1971 12:49:40 GMT+0200 (Eastern European Standard Time) Date: 27/12/1971 12:49:40 

Related Article — JavaScript Date

Источник

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