How to convert date to timestamp?
Did you use Date(myDate).getTime() (what you’ve marked up as code), or is the word «new» prior to it meant to be part of the code? The more effort you put in, the better the answers you get will be.
@rsbarro: Except it doesn’t seem to be maintained anymore (and there are outstanding bugs). MomentJS seems quite good, though.
@T.J.Crowder I’ve used date.js and it’s worked for what I’ve needed it for, but you’re right it has not been actively worked on in some time. I will check out momentjs. Thanks!
25 Answers 25
Split the string into its parts and provide them directly to the Date constructor:
var myDate = "26-02-2012"; myDate = myDate.split("-"); var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]); console.log(newDate.getTime());
Unfortunately, this does not work in Safari5, as it returns NaN . In Safari you have to use the other possible constructor new Date(year, month, day); , regarding this example: new Date(myDate[2], myDate[1], myDate[0]);
Instead of converting the date string from «European» to «American» format, it’s better to convert it to ISO 8601 format ( YYYY-MM-DD ), which is guaranteed to be understood by Date() , and is, generally speaking, the most interoperable format for date strings.
Try this function, it uses the Date.parse() method and doesn’t require any custom logic:
function toTimestamp(strDate) < var datum = Date.parse(strDate); return datum/1000; >alert(toTimestamp('02/13/2009 23:31:30'));
@RobG can you please include an argument why it is not recommended? This would add value and understanding to your comment.
why have you chosen to use that date format? I want to understand you used mm/dd/yyyy, right? Why the reason? Does using a different format has an effect?
this refactored code will do it
let toTimestamp = strDate => Date.parse(strDate)
this works on all modern browsers except ie8-
Great answer. Note it creates a millisecond timestamp. For a timestamp with seconds accuracy you can Date.parse(strDate) / 1000; instead of Date.parse(strDate) .
There are two problems here. First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.
Second, you need to pass it a string in a proper format.
UPDATE: In case you came here looking for current timestamp
Date.now(); //as suggested by Wilt
var date = new Date(); var timestamp = date.getTime();
new Date().getTime(); /* console.log(new Date().getTime()); */
Yes or simply: Date.now() which makes your two suggestions suddenly look very complicated. Visit for more details on this function the documentation on MDN here.
You need just to reverse your date digit and change — with , :
new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)
var myDate="26-02-2012"; myDate=myDate.split("-"); new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();
P.S. UK locale does not matter here.
That date format is also invalid, and won’t work reliably cross-browser and cross-locale (it doesn’t, for instance, for me in Chrome with the UK locale). If you’re going to suggest a format, suggest one that’s actually documented to work.
I get the example from developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…. I just forgot to put away the string. Now it works.
Okay, at least now the code above isn’t using an invalid date format — it’s just giving the wrong date, for two separate reasons. Above you’ve defined the date March 2nd, 2014 (you have the field order messed up). And if the fields were in the right order, you’d be defining the date March 26th, 2012 (month values start at zero). But as the OP has a string, not a series of numbers, it’s not all that useful even if you addressed those issues.
@T.J. Crowder thanks for your suggestions. I fixed the code as you said converting the String to a Number. Merci.
The first code example is still wrong, and using Number on strings starting with a 0 is problematic on some engines — use parseInt and specify a radix.
To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k.
I had to devide it by 1000: new Date(‘2012-02-26’).getTime() / 1000
JUST A REMINDER
Your string isn’t in a format that the Date object is specified to handle. You’ll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29 ) before asking Date to parse it.
Why you’re getting NaN : When you ask new Date(. ) to handle an invalid string, it returns a Date object which is set to an invalid date ( new Date(«29-02-2012»).toString() returns «Invalid date» ). Calling getTime() on a date object in this state returns NaN .
@benvds: Cool, thanks. Although I find the comment «Also, it is non-destructive to the DOM» a bit odd. I expect what they meant was that it doesn’t change the Date object (which has nothing to do with the DOM).
For those who wants to have readable timestamp in format of, yyyymmddHHMMSS
> (new Date()).toISOString().replace(/[^\d]/g,'') // "20190220044724404" > (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724" > (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"
Usage example: a backup file extension. /my/path/my.file.js.20190220
How to convert date to epoch time in typescript?
Today, we are going to learn How to convert date to epoch time in typescript, here we will use built-in method Date.parse() method to convert date to epoch time.
First of all, let understand what is a epoch time?
The Unix epoch or Unix time is the number of seconds elapsed since January 1, 1970. The getTime() method is used to return the millisecond representation of the Date object.31
So First we will create a date variable, and then we will use Date.parse() method to convert date to epoch time.
let date = new Date(); console.log(date); // 2022-04-26T08:49:11.282Z let numDate: number = Date.parse(date); console.log(numDate) // 1650962945000
Well, when you run above code, you can able to see date converted in epoch time format.
For now, let’s check the output.
Output#
TypeScript, convert date to epoch time example
How to convert date to timestamp in typescript?
Today, we are going to learn How to convert a date to the timestamp in typescript?, here we will use the date built-in method Date.parse() method to convert the date to timestamp format.
So, let’s see what is Date.parse() method is?
The Date.parse() method parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Here, there is an easier way of getting the timestamp by using the parse() function. This function returns the timestamp in milliseconds, so we need to divide it by 1000 in order to get the timestamp.
const toTimestamp = (strDate: string) => var datum: number = Date.parse(strDate); return datum / 1000; > toTimestamp('06/14/2022 11:28:10')
Well, when you run the above code, you can able to see the date convert in timestamp format. For now, let’s check the output.
Output#
TypeScript, convert date to timestamp example
Typescript date to timestamp
TypeScript is a is an open-source programming langauge. It builds on JavaScript with the goal for the development of large applications and transcompiles to JavaScript. In TypeScript, the Date() object represents a date and time functionality.
- Epoch and Date Time Conversion in PHP
- Epoch and Date Time Conversion in JavaScript
- Epoch and Date Time Conversion in Perl
- Epoch and Date Time Conversion in Python
- Epoch and Date Time Conversion in Go
- Epoch and Date Time Conversion in Java
- Epoch and Date Time Conversion in Ruby
- Epoch and Date Time Conversion in MySQL
- Epoch and Date Time Conversion in SQL Server
- Epoch and Date Time Conversion in VBA
- Epoch and Date Time Conversion in Rust
- Epoch and Date Time Conversion in Kotlin
- Epoch and Date Time Conversion in Matlab
Here we will explain TypeScript date time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.
Get current epoch or Unix timestamp in TypeScript
You can get the current timestamp using Date() object and getTime() in TypeScript like below:
Convert epoch or Unix timestamp to date in TypeScript
You can also convert unix timestamp to date using Date() object in TypeScript like below:
let unixTimestamp = 1624705077;
let formattedDate = new Date(unixTimestamp * 1000);
Convert date to epoch or unix timestamp in TypeScript
You can convert date to unix timestamp using Date() object and getTime() function TypeScript.
Convert date to timestamp for storing into firebase firestore in javascript
I’m currently using Math.floor(Date.now() / 1000) to get the correct timestamp format to add into a document in Firebase, however, the timestamp gets inserted as a number, and not as a timestamp. I would like to have it inserted as shown below (as a timestamp, not as a number).
Is this possible?
@E.Maggini This is not a duplicate of that question. This question is not about converting a timestamp to a date but about saving the timestamp in Firestore as a timestamp instead of a number.
Thanks everyone, I’ll checkout the Timestamp documentation for converting. I cannot use the firebase.database.ServerValue.TIMESTAMP value because some of the dates I’m using aren’t the current dates.
11 Answers 11
You can simply use the following line:
var myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());
.fromDate is a static method from the static Timestamp class from Firebase.
For cloud functions look at JGuo’s comment:
If you are writing cloud functions, it becomes admin.firestore.Timestamp.fromDate() – JGuo Jan 21 at 1:56
Thank you this is the simplest solution and exactly what I was looking for! For some reason the documentation I found said you passed the date in via the constructor not via a static method.
Sending new Date() or Date.now() directly is totally enough. Firebase/Firestore handle the convertion to a timestamp on his own. Plus you can use moment.js to handle all your date manipulation
agreed that sending new Date() is enough, but Typescript wants a type — either Date or firebase.firestore.Timestamp (could use a union type but don’t like to)
If you want to store a field as a timestamp in Firestore, you’ll have to send a JavaScript Date object or a Firestore Timestamp object as the value of the field.
If you want to use Date, simply say new Date(x) where x is the value in milliseconds that you were trying to add before.
If you want to use Timestamp, you would have to do more work to get that x converted into a combination of seconds and nanoseconds to pass to the constructor, as the documentation suggests.
This is a bit old but just figure out how to do this in a Svelte project. I assume this would also work in a React project (sorry don’t know much about Vue). The kicker is that I am using Web version 9.
import < Timestamp >from "@firebase/firestore"; let noteDate = Timestamp.fromDate(new Date());
Just for context. I am adding this new note object to the UI. When it was just a javascript date it worked fine with firebase but I could not call the required .toDate() without seeing an UI error.
So making this a firebase.Timestamp was my way of avoiding the UI error when calling .toDate on a javascript date object.