275

I want to convert date to timestamp, my input is 26-02-2012. I used

new Date(myDate).getTime();

It says NaN.. Can any one tell how to convert this?

Dharman
  • 30,962
  • 25
  • 85
  • 135
selladurai
  • 6,491
  • 14
  • 56
  • 88
  • 1
    possible duplicate of http://stackoverflow.com/questions/9343971/timestamp-conversion-javascript – Bogdan Emil Mariesan Mar 26 '12 at 13:40
  • you may want to take a look at the date.js library: http://www.datejs.com/ – rsbarro Mar 26 '12 at 13:41
  • 1
    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. – T.J. Crowder Mar 26 '12 at 13:41
  • @rsbarro: Except it doesn't seem to be maintained anymore (and there are outstanding bugs). [MomentJS](http://momentjs.com/) seems quite good, though. – T.J. Crowder Mar 26 '12 at 13:42
  • @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! – rsbarro Mar 26 '12 at 15:40
  • @rsbarro: This is the one (a parsing bug) that bit me: http://jsbin.com/inudib The version used on the datejs.com home page is different from the latest "release" and doesn't have this problem (but has others that the latest "release" doesn't). – T.J. Crowder Mar 26 '12 at 16:25
  • You need parenthesis around the `new Date()` ... So like, `(new Date("2022-03-02")).getTime()` – SeanMC Mar 16 '22 at 00:26

25 Answers25

299

Split the string into its parts and provide them directly to the Date constructor:

Update:

var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
RobG
  • 142,382
  • 31
  • 172
  • 209
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • 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]);` – insertusernamehere Aug 20 '12 at 11:18
  • 20
    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. – Walter Tross Dec 04 '14 at 13:54
  • 9
    Note: `new Date(newDate).getTime()` will produce a timestamp in millisecond resolution. – h7r Dec 22 '14 at 09:36
  • 6
    For seconds use: `Math.floor(new Date(newDate).getTime() / 1000)` – metamagikum Aug 19 '15 at 20:28
  • 3
    C'mon, seriously they should really think of a better naming instead of getTime()! – Farzan Jul 05 '21 at 22:25
97

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'));
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Ketan Savaliya
  • 1,190
  • 9
  • 11
  • 2
    Using the built–in parser is not recommended. – RobG Aug 23 '20 at 23:44
  • 5
    @RobG can you please include an argument _why_ it is not recommended? This would add value and understanding to your comment. – dimib Dec 16 '20 at 17:06
  • 1
    @dimib—see [this answer](https://stackoverflow.com/a/2587398/257182) to [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). – RobG Dec 16 '20 at 23:15
  • 1
    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? – Karue Benson Karue Feb 16 '22 at 00:02
51

this refactored code will do it

let toTimestamp = strDate => Date.parse(strDate)

this works on all modern browsers except ie8-

Jalasem
  • 27,261
  • 3
  • 21
  • 29
  • 1
    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)`. – Mike Poole Nov 05 '22 at 06:51
23

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.

Working example:

(new Date("2012-02-26")).getTime();
Alan Bogu
  • 705
  • 5
  • 9
19

UPDATE: In case you came here looking for current timestamp

Date.now(); //as suggested by Wilt

or

var date      = new Date();
var timestamp = date.getTime();

or simply

new Date().getTime();
/* console.log(new Date().getTime()); */
Timetrax
  • 1,373
  • 13
  • 15
  • 1
    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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now). – Wilt Jan 24 '23 at 11:41
12

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)

In your case:

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.

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
antonjs
  • 14,060
  • 14
  • 65
  • 91
  • 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. – T.J. Crowder Mar 26 '12 at 13:47
  • I get the example from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date. I just forgot to put away the string. Now it works. – antonjs Mar 26 '12 at 13:52
  • 2
    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 Mar 26 '12 at 14:04
  • @T.J. Crowder thanks for your suggestions. I fixed the code as you said converting the String to a Number. Merci. – antonjs Mar 26 '12 at 14:08
  • 2
    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. – T.J. Crowder Mar 26 '12 at 14:09
  • **Again**: The first code example is still wrong. With respect, this is not helpful, recommend just deleting and moving on -- or, of course, really rigorously thinking it through and double-checking yourself. Bad advice is usually worse than no advice. – T.J. Crowder Mar 26 '12 at 14:16
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/9324/discussion-between-antojs-and-t-j-crowder) – antonjs Mar 26 '12 at 14:20
  • please note that in the second part it most certainly should be `parseInt(myDate[0], 10))` instead of `parseInt(myDate[0]), 10)`, otherwise 10 would not be the radix but the next argument of the `Date()` constructor, which is the hour – Mallard Mar 26 '14 at 13:34
  • Finally got to a decent answer, but *parseInt* isn't necessary, just pass the values to the constructor (but still subtract 1 from the month number). :-) – RobG Aug 23 '20 at 23:51
8

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

orszaczky
  • 13,301
  • 8
  • 47
  • 54
6
function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
deepakssn
  • 5,195
  • 2
  • 24
  • 19
5

JUST A REMINDER

Date.parse("2022-08-04T04:02:10.909Z")

1659585730909

Date.parse(new Date("2022-08-04T04:02:10.909Z"))

1659585730000

hkniyi
  • 263
  • 3
  • 7
4

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

allenhwkim
  • 27,270
  • 18
  • 89
  • 122
  • Be aware that toISOString converts your date to UTC, so might not always have the desired outcome. – Bunker Dec 09 '20 at 08:34
4

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @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). – T.J. Crowder Mar 26 '12 at 14:06
3

The below code will convert the current date into the timestamp.

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
mukhtar alam
  • 195
  • 1
  • 12
  • 1
    Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues. – FluffyKitten Aug 21 '20 at 19:27
2
/**
 * Date to timestamp
 * @param  string template
 * @param  string date
 * @return string
 * @example         datetotime("d-m-Y", "26-02-2012") return 1330207200000
 */
function datetotime(template, date){
    date = date.split( template[1] );
    template = template.split( template[1] );
    date = date[ template.indexOf('m') ]
        + "/" + date[ template.indexOf('d') ]
        + "/" + date[ template.indexOf('Y') ];

    return (new Date(date).getTime());
}
Evgeniy
  • 21
  • 2
2

The first answer is fine however Using react typescript would complain because of split('') for me the method tha worked better was.

parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))

Happy to help.

Diego Braga
  • 161
  • 11
2

In some cases, it appears that some dates are stubborn, that is, even with a date format, like "2022-06-29 15:16:21", you still get null or NaN. I got to resolve mine by including a "T" in the empty space, that is:

const inputDate = "2022-06-29 15:16:21";
const newInputDate = inputDate.replace(" ", "T");

const timeStamp = new Date(newInputDate).getTime();

And this worked fine for me! Cheers!

BigBenny O
  • 21
  • 2
1

It should have been in this standard date format YYYY-MM-DD, to use below equation. You may have time along with example: 2020-04-24 16:51:56 or 2020-04-24T16:51:56+05:30. It will work fine but date format should like this YYYY-MM-DD only.

var myDate = "2020-04-24";
var timestamp = +new Date(myDate)
ANIL PATEL
  • 673
  • 7
  • 16
1

You can use valueOf method

new Date().valueOf()
Luka Samkharadze
  • 111
  • 1
  • 12
1

Here I am converting the current date to a timestamp and then I take the timestamp and convert it to the current date back, with us showing how to convert date to timestamp and timestamp to date.

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

var actual = new Date(timestamp)
console.log(actual) // Tue Jun 07 2022 18:18:38 GMT-0300 (Horário Padrão de Brasília)
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Gama
  • 51
  • 1
  • 5
  • NOTE:: Date.parse("2022-08-04T04:02:10.909Z") >> 1659585730909 While Date.parse(new Date("2022-08-04T04:02:10.909Z")) >> 1659585730000 – hkniyi Aug 04 '22 at 17:35
1

The simplest and accurate way would be to add the unary operator before the date

console.log(`Time stamp is: ${Number(+new Date())}`)
0

Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:

var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000
Frederick Eze
  • 121
  • 1
  • 12
0

Simply performing some arithmetic on a Date object will return the timestamp as a number. This is useful for compact notation. I find this is the easiest way to remember, as the method also works for converting numbers cast as string types back to number types.

let d = new Date();
console.log(d, d * 1);
OXiGEN
  • 2,041
  • 25
  • 19
0

This would do the trick if you need to add time also new Date('2021-07-22 07:47:05.842442+00').getTime()

This would also work without Time new Date('2021-07-22 07:47:05.842442+00').getTime()

This would also work but it won't Accept Time new Date('2021/07/22').getTime()

And Lastly if all did not work use this new Date(year, month, day, hours, minutes, seconds, milliseconds)

Note for Month it the count starts at 0 so Jan === 0 and Dec === 11

Daniel Adegoke
  • 179
  • 1
  • 4
0

+new Date(myDate) this should convert myDate to timeStamp

0

it that simple but you have to make sure to use american date format

    function MygetTime(date){
return (new Date(date).getTime())
}
console.log(MygetTime("03-13-2023"))
0

I use this to get my time stamp: Date.parse("2000-03-04 09:10:43")/1000;

Dexter
  • 74
  • 8