selladurai
selladurai

Reputation: 6779

How to convert date to timestamp?

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?

Upvotes: 295

Views: 873027

Answers (26)

Christopher
Christopher

Reputation: 193

2024 UPDATE

No package needed

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

Upvotes: 0

hkniyi
hkniyi

Reputation: 353

JUST A REMINDER

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

Date.parse(new Date("2022-08-04T04:02:10.909Z"))
// 1659585730000 (milliseconds are ignored)

Upvotes: 8

The Alpha
The Alpha

Reputation: 146191

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());

Updated: Also, you can use a regular expression to split the string, for example:

const dtStr = "26/02/2012";
const [d, m, y] = dtStr.split(/-|\//); // splits "26-02-2012" or "26/02/2012"
const date = new Date(y, m - 1, d);
console.log(date.getTime());

Upvotes: 318

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

Upvotes: 0

Gama
Gama

Reputation: 61

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)

Upvotes: 1

Muhammed RYHAN
Muhammed RYHAN

Reputation: 117

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

Upvotes: 0

Timetrax
Timetrax

Reputation: 1493

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()); */

Upvotes: 19

Vishal Jayapalan
Vishal Jayapalan

Reputation: 1

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

Upvotes: 0

Justin Bashombana
Justin Bashombana

Reputation: 181

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

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

Upvotes: 1

BigBenny O
BigBenny O

Reputation: 21

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!

Upvotes: 2

Luka Samkharadze
Luka Samkharadze

Reputation: 76

You can use valueOf method

new Date().valueOf()

Upvotes: 1

Daniel Adegoke
Daniel Adegoke

Reputation: 199

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

Upvotes: 0

Diego Braga
Diego Braga

Reputation: 221

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.

Upvotes: 2

antonjs
antonjs

Reputation: 14318

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.

Upvotes: 12

ANIL PATEL
ANIL PATEL

Reputation: 743

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)

Upvotes: 1

OXiGEN
OXiGEN

Reputation: 2399

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

Upvotes: 0

mukhtar alam
mukhtar alam

Reputation: 323

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

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);

Upvotes: 3

allenhwkim
allenhwkim

Reputation: 27738

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

Upvotes: 4

Frederick Eze
Frederick Eze

Reputation: 131

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

Upvotes: 0

orszaczky
orszaczky

Reputation: 15615

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

Upvotes: 8

Alan Bogu
Alan Bogu

Reputation: 775

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();

Upvotes: 29

Ketan Savaliya
Ketan Savaliya

Reputation: 1210

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'));

Upvotes: 99

Jalasem
Jalasem

Reputation: 28381

this refactored code will do it

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

this works on all modern browsers except ie8-

Upvotes: 55

Evgeniy
Evgeniy

Reputation: 21

/**
 * 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());
}

Upvotes: 2

deepakssn
deepakssn

Reputation: 5363

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())));
}

Upvotes: 6

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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.

Upvotes: 4

Related Questions