- JavaScript Timestamp – How to Use getTime() to Generate Timestamps in JS
- How to Use getTime() to Generate Timestamps in JS
- How to Use Date.now() to Generate Timestamps in JS
- How to Use valueOf() to Generate Timestamps in JS
- Summary
- How to timestamp in javascript
- # Table of Contents
- # Convert a Date to a Timestamp using JavaScript
- # Converting the timestamp to seconds
- # Convert a Date string to a Timestamp in JavaScript
- # Convert a Date and Time string to a Timestamp in JavaScript
- # Additional Resources
- How to Convert Date to Unix Timestamp in JavaScript
- Methods to Convert Date to Unix Timestamp in JavaScript
- 1. Math.floor() Method
- 2. Custom Function to Convert Date to Unix TimeStamp
- 3. Custom Function to Convert Datetime to Unix TimeStamp
- 4. Moment.js Library
- Conclusion
JavaScript Timestamp – How to Use getTime() to Generate Timestamps in JS
Ihechikara Vincent Abba
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
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.
How to timestamp in javascript
Last updated: Jan 13, 2023
Reading time · 3 min
# 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).
# 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:
- 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.
- 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 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:
- Create a Date object via the Date constructor taking in any acceptable date formats.
- 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:
- Create a function toUnixTime that takes in year , month and day .
- 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 .
- For month , we will subtract 1 from the input. As Date() take in month starting from 0 representing January.
- 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:
- Create a function toUnixTime that takes in year , month and day , hour , min , sec .
- 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 .
- For month , we will subtract 1 from the input. As Date() take in month starting from 0 representing January.
- 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.