Javascript datetime to unix

Javascript datetime to unix

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).

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

Читайте также:  Opencv modules highgui src window cpp

# 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.

Источник

How to get the Unix timestamp in JavaScript

The Unix timestamp is an integer value that represents the number of seconds elapsed since the Unix Epoch on January 1st, 1970, at 00:00:00 UTC. In short, a Unix timestamp is the number of seconds between a specific date and the Unix Epoch.

The JavaScript Date object provides several methods to manipulate date and time. You can get the current timestamp by calling the now() function on the Date object like below:

This method returns the current UTC timestamp in milliseconds. The Date.now() function works in almost all modern browsers except IE8 and earlier versions. But you can fix this by writing a small polyfill:

if(!Date.now)  Date.now = () => new Date().getTime() > 

Otherwise, you can get the same timestamp by calling other JavaScript functions that work in older browsers too:

const timestamp = new Date().getTime() // OR const timestamp = new Date().valueOf() 

To convert the timestamp to seconds (Unix time), you can do the following:

const unixTime = Math.floor(Date.now() / 1000) 

The unixTime variable now contains the Unix timestamp for the current date and time, depending on the user’s web browser.

It is recommended to use Date.now() whenever possible, even with polyfill. Unlike the getTime() method, it is shorter and doesn’t create a new instance of the Date object.

If you are using a Unix-compatible machine like Ubuntu or macOS, you can also get the current Unix timestamp by typing the following command in your terminal:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

JavaScript Timestamp – How to Use getTime() to Generate Timestamps in JS

Ihechikara Vincent Abba

Ihechikara Vincent Abba

JavaScript Timestamp – How to Use getTime() to Generate Timestamps in JS

In JavaScript, timestamps are usually associated with Unix time. And there are different methods for generating such timestamps.

When we make use of the different JavaScript methods for generating timestamps, they return the number of milliseconds that has passed since 1 January 1970 UTC (the Unix time).

In this article, you’ll learn how to use the following methods to generate Unix timestamps in JavaScript:

How to Use getTime() to Generate Timestamps in JS

var timestamp = new Date().getTime(); console.log(timestamp) // 1660926192826

In the example above, we created a new Date() object and stored it in a timestamp variable.

We also attached the getTime() method to the new Date() object using dot notation: new Date().getTime() . This returned the Unix time at that point in milliseconds: 1660926192826.

To get the timestamp in seconds, you divide the current timestamp by 1000. That is:

var timestamp = new Date().getTime(); console.log(Math.floor(timestamp / 1000)) 

How to Use Date.now() to Generate Timestamps in JS

var timestamp = Date.now(); console.log(timestamp) // 1660926758875

In the example above, we got the Unix timestamp at that particular point in time using the Date.now() method.

The timestamps you see in these examples will be different from yours. This is because you’ll get the timestamp of the time that has elapsed from 1 January 1970 UTC to your current time.

How to Use valueOf() to Generate Timestamps in JS

var timestamp = new Date().valueOf(); console.log(timestamp) // 1660928777955

Just like the getTime() method, we have to attach the valueOf() method to a new Date() object in order to generate a Unix timestamp.

The new Date() object, without getTime() or valueOf() , returns the information about your current time.

Summary

In the article, we talked about timestamps in JavaScript. There are usually associated with the Unix time.

We saw three different methods that can be used to generate timestamps in JavaScript with code examples.

Ihechikara Vincent Abba

Ihechikara Vincent Abba

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

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