Javascript unix time to date time

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.

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.

Читайте также:  Иконки соцсетей html css

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.

Источник

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:

  1. Convert the unix timestamp into milliseconds by multiplying it by 1000 .
  2. Use the newly created milliseconds value to create a date object with the new Date() constructor method.
  3. 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.

Читайте также:  Http basic auth with php

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.

Читайте также:  Декораторы typescript простым языком

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 Unix timestamp to time in JavaScript ?

In this article, we will see how to convert UNIX timestamps to time using 2 approaches:

Method 1: Using the toUTCString() method

As JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object. The toUTCString() method is used to represent the Date object as a string the UTC time format. The time from this date string can be found by extracting from the 11th to last to the 4th to the last character of the string. This is extracted using the slice() function. This string is the time representation of the UNIX timestamp.

dateObj = new Date(unixTimestamp * 1000); utcString = dateObj.toUTCString(); time = utcString.slice(-11, -4);

Javascript

Method 2: Getting individual hours, minutes and seconds

As JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object. Each part of the time is extracted from the Date object. The hour’s value in UTC is extracted from the date using the getUTCHours() method. The minute’s value in UTC is extracted from the date using the getUTCMinutes() method. The second’s value in UTC is extracted from the date using the getUTCSeconds() method. The final formatted date is created by converting each of these values to a string using the toString() method and then padding them with an extra ‘0’, if the value is a single-digit by using the padStart() method. The individual parts are then joined together with a colon(:) as the separator. This string is the time representation of the UNIX timestamp.

dateObj = new Date(unixTimestamp * 1000); // Get hours from the timestamp hours = dateObj.getUTCHours(); // Get minutes part from the timestamp minutes = dateObj.getUTCMinutes(); // Get seconds part from the timestamp seconds = dateObj.getUTCSeconds(); formattedTime = hours.toString() .padStart(2, '0') + ':' + minutes.toString() .padStart(2, '0') + ':' + seconds.toString() .padStart(2, '0');

Источник

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