Convert to javascript timestamp

Convert to javascript timestamp

Last updated: Jan 13, 2023
Reading time · 3 min

banner

# Table of Contents

# Convert a Date to a Timestamp using JavaScript

Use the getTime() method to convert a date to a timestamp, e.g. new Date().getTime() .

The getTime method returns the number of milliseconds elapsed between the 1st of January, 1970 and the given date.

Copied!
const str = '2022-04-26'; const date = new Date(str); // ✅ Get timestamp in Milliseconds const timestamp = date.getTime(); console.log(timestamp); // 👉️ 1650931200000 // ✅ If you need to convert milliseconds to seconds // divide by 1000 const unixTimestamp = Math.floor(date.getTime() / 1000); console.log(unixTimestamp); // 👉️ 1650931200

To convert a Date to a timestamp, you need to have a Date object.

If you have a date string, pass it to the Date() constructor to get a Date object.

If you get an invalid Date when creating the Date object, you need to format the string correctly before passing it to the Date() constructor (more on that below).

Читайте также:  Java file new file url

The getTime method returns the number of milliseconds since the Unix Epoch (1st of January, 1970 00:00:00).

# Converting the timestamp to seconds

If you need to convert the result to seconds, divide it by 1000 .

Copied!
const str = '2022-04-26'; const date = new Date(str); // ✅ If you need to convert to Seconds const timestampSeconds = Math.floor(date.getTime() / 1000); console.log(timestampSeconds); // 👉️ 1650931200

In short, to convert a Date to a timestamp, all you have to do is call the getTime() method on the Date .

# Convert a Date string to a Timestamp in JavaScript

If you have difficulties creating a valid Date object, you can pass 2 types of parameters to the Date() constructor:

  1. a valid ISO 8601 string, formatted as YYYY-MM-DDTHH:mm:ss.sssZ , or just YYYY-MM-DD , if you only have a date without time.
  2. multiple, comma-separated parameters that represent the year , month (0 = January to 11 = December), day of the month , hours , minutes and seconds .

Here is an example that splits a string and passes the parameters to the Date() constructor to create a Date object.

Copied!
// 👇️ Formatted as MM/DD/YYYY const str = '04/16/2022'; const [month, day, year] = str.split('/'); const date = new Date(+year, month - 1, +day); console.log(date); // 👉️ Sat Apr 16 2022 // ✅ Get timestamp const timestamp = date.getTime(); console.log(timestamp); // 👉️ 1650056400000

We have a date string that is formatted as MM/DD/YYYY , so we split the string on each forward slash to get an array of substrings containing the month, day and year.

We have a date string formatted as MM/DD/YYYY in the example, but this can be any other format.

We passed the values as the first 3 parameters to the Date() constructor to create a valid Date object, so we can get a timestamp by calling the getTime() method.

Once you manage to create a Date object from the date string, getting a timestamp is as easy as calling the getTime() method.

Notice that we subtracted 1 from the month when passing it to the Date() constructor.

This is because, the Date constructor expects a zero-based value, where January = 0, February = 1, March = 2, etc.

# Convert a Date and Time string to a Timestamp in JavaScript

If you also have time-related data, e.g. hours, minutes and seconds, pass them to the Date() constructor as well.

Copied!
// 👇️ Formatted as MM/DD/YYYY hh:mm:ss const str = '04/16/2022 06:45:12'; const [dateComponents, timeComponents] = str.split(' '); console.log(dateComponents); // 👉️ "04/16/2022" console.log(timeComponents); // 👉️ "06:45:12" const [month, day, year] = dateComponents.split('/'); const [hours, minutes, seconds] = timeComponents.split(':'); const date = new Date(+year, month - 1, +day, +hours, +minutes, +seconds); console.log(date); // 👉️ Sat Apr 16 2022 06:45:12 // ✅ Get timestamp const timestamp = date.getTime(); console.log(timestamp); // 👉️ 1650080712000

The first thing we did was split the date and time string on the space, so we can get the date and time components as separate strings.

We then had to split the date string on each forward slash to get the value for the month, day and year. Note that your separator might be different, e.g. a hyphen, but the approach is the same.

We also split the time string on each colon and assigned the hours, minutes and seconds to variables.

We passed all of the parameters to the Date() constructor to create a Date object and got the timestamp by calling the getTime() method.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Convert to javascript timestamp

Last updated: Jan 13, 2023
Reading time · 2 min

banner

# Convert an ISO Date to a Timestamp using JavaScript

Use the getTime() method to convert an ISO date to a timestamp.

The getTime method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.

Copied!
const isoStr = '2022-07-21T09:35:31.820Z'; const date = new Date(isoStr); const timestamp = date.getTime(); console.log(timestamp); // 👉️ 165839613182

We used the Date() constructor to parse an ISO string and get a Date object.

The getTime method returns the number of milliseconds between the 1st of January, 1970 and the given date.

The getTime method always uses UTC for time representation. In other words, the time zone of the visitor’s browser doesn’t change the value the method returns.

# Removing the offset from the timestamp

If you need to remove the offset from the timestamp, use this approach instead.

Copied!
const isoStr1 = '2022-07-21T09:35:31.820Z'; const date = new Date(isoStr1); const timestampWithOffset = date.getTime(); const offset = date.getTimezoneOffset() * 60 * 1000; console.log(offset); // 👉️ -10800000 const timestampWithoutOffset = timestampWithOffset - offset; const dateWithOffset = new Date(timestampWithOffset); console.log(dateWithOffset); // 👉️ Thu Jul 21 2022 12:35:31 GMT+0300 const dateWithoutOffset = new Date(timestampWithoutOffset); console.log(dateWithoutOffset); // 👉️ Thu Jul 21 2022 15:35:31 GMT+0300

The getTimezoneOffset method returns the difference, in minutes, between a date (evaluated in UTC) and the same date evaluated in the visitor’s local time zone.

If you get a value like -120 , then the time zone offset is UTC+02.

Similarly, for a value of -60 , the time zone offset is UTC+01.

We converted the offset to milliseconds and subtracted it from the UTC timestamp to get a timestamp without the offset.

# Using getTime() to avoid mutating dates

The getTime() method can also be used to copy the date and time from one Date object to another.

Copied!
const isoStr = '2022-07-21T09:35:31.820Z'; const date = new Date(isoStr); console.log(date); // 👉️ Thu Jul 21 2022 12:35:31 GMT+0300 const timestamp = date.getTime(); console.log(timestamp); // 👉️ 165839613182 const dateCopy = new Date(timestamp); console.log(dateCopy); // 👉️ Thu Jul 21 2022 12:35:31 GMT+0300

Cloning a Date object is very useful when you want to avoid mutating it in place with some of the set* methods, e.g. setHours() .

You can also use the getTime method to compare dates.

Copied!
const isoStr1 = '2022-07-21T09:35:31.820Z'; const isoStr2 = '2023-04-24T10:30:00.820Z'; const date1 = new Date(isoStr1); const date2 = new Date(isoStr2); console.log(date1.getTime() > date2.getTime()); // 👉️ false console.log(date1.getTime() === date2.getTime()); // 👉️ false console.log(date1.getTime() date2.getTime()); // 👉️ true

The examples show how to compare dates using their Unix timestamp.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Convert Date to Unix Timestamp in JavaScript

How to Convert Date to Unix Timestamp in JavaScript

There are 4 ways to easily convert data to Unix Timestamp in JavaScript. Let’s explore the methods.

Methods to Convert Date to Unix Timestamp in JavaScript

Here are the list of 4 methods where we can easily convert date to Unix timestamp. Since each of them have their own properties and features, we can choose which to use depending on our needs.

  • Math.floor() Method
  • Custom Function to Convert Date to Unix TimeStamp
  • Custom Function to Convert Datetime to Unix TimeStamp
  • Moment.js Library

Let’s look into each details with illustration below.

1. Math.floor() Method

Math.floor() is part of original Math standard built-in object method in JavaScript. Combining with getTime() method of Date object, we will be able to retrieve Unix timestamp in seconds.

Process Flow:

  1. Create a Date object via the Date constructor taking in any acceptable date formats.
  2. We use getTime() method to retrieve the time in millisecond. Then we will divide the result by 1000 and use Math.floor() to remove all decimal values.
const date = new Date('2021-06-16'); const timeInMillisecond = date.getTime(); const unixTimestamp = Math.floor(date.getTime() / 1000); console.log(unixTimestamp); // 1623801600

2. Custom Function to Convert Date to Unix TimeStamp

We can create a common function to take in year, month and date that is reusable across whole codebase.

Process Flow:

  1. Create a function toUnixTime that takes in year , month and day .
  2. Inside toUnixTime function, we will create a Date object via the Date constructor taking in year , month and day . We will assume all pass-in parameter are UTC values by using Date.UTC .
  3. For month , we will subtract 1 from the input. As Date() take in month starting from 0 representing January.
  4. We use getTime() method to retrieve the time in millisecond. Then we will divide the result by 1000 and use Math.floor() to remove all decimal values.
const toUnixTime = (year, month, day) => < const date = new Date(Date.UTC(year, month - 1, day)); return Math.floor(date.getTime()/1000); >const unixTimestamp = toUnixTime(2022, 12, 31); console.log(unixTimestamp); // 1672444800

3. Custom Function to Convert Datetime to Unix TimeStamp

To convert datetime to Unix Timestamp, it will be similar to the above method. However, we will also take in hour, minutes and seconds as parameters.

Process Flow:

  1. Create a function toUnixTime that takes in year , month and day , hour , min , sec .
  2. Inside toUnixTime function, we will create a Date object via the Date constructor taking in all 6 parameters. We will assume all pass-in parameter are UTC values by using Date.UTC .
  3. For month , we will subtract 1 from the input. As Date() take in month starting from 0 representing January.
  4. We use getTime() method to retrieve the time in millisecond. Then we will divide the result by 1000 and use Math.floor() to remove all decimal values.
const toUnixTime = (year, month, day, hr, min, sec) => < const date = new Date(Date.UTC(year, month - 1, day, hr, min, sec)); return Math.floor(date.getTime()/1000); >const unixTimestamp = toUnixTime(2022, 12, 31, 12, 33, 0); console.log(unixTimestamp); // 1672489980

4. Moment.js Library

If we can use external library, Moment.js provides a very simple method for us to retrieve the Unix time from current or any date. unix() is the method we can use to retrieve dates in Unix timestamp in seconds.

Below shows the examples where we convert the current date, a specify date-string and unix milliseconds to unix seconds.

import moment from 'moment'; // Convert current time to Unix let timestamp = moment().unix(); console.log(timestamp); // 1651648727 // Convert datestring to unix seconds timestamp = moment('2022-04-16').unix(); console.log(timestamp); // 1650038400 // Convert a unix time in millisecond to second timestamp = moment(1314535498806).unix(); console.log(timestamp); // 1314535498

Conclusion

We have look into 4 different methods to convert date to Unix Timestamp in JavaScript.

The easiest method is by using Moment.js library but we need to install a dependency. The next good option is to create a custom function since it will be reusable and also encapsulate the logic from external code.

Источник

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