96

In PHP, you can easily convert an English textual datetime description into a proper date with strtotime().

Is there anything similar in Javascript?

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
VJS
  • 1,131
  • 4
  • 11
  • 20
  • For parsing from the format dd.mm.yyyy, check http://stackoverflow.com/questions/1576753/parse-datetime-string-in-javascript – Valentin Despa Feb 07 '13 at 09:52

9 Answers9

68

There is not. The closest built-in option is Date.parse(), which parses a very limited subset of what strtotime() can:

var ts = Date.parse("2010-10-29");

It's worth noting that this function returns milliseconds instead of seconds, so you need to divide the result by 1000 to get an equivalent value to PHP's function.

miken32
  • 42,008
  • 16
  • 111
  • 154
Arnaldo
  • 817
  • 6
  • 8
  • 37
    Nope; this works very different than php strtotime, none of the examples of the php documentation work, not a single one `strtotime("now"); strtotime("10 September 2000"); strtotime("+1 day"); strtotime("+1 week"); strtotime("+1 week 2 days 4 hours 2 seconds"); strtotime("next Thursday"); strtotime("last Monday");` – Ivan Castellanos Jan 04 '14 at 00:47
  • This should work, but it's unreliable. Date.parse('2020-06-06') should return the same timestamp as Date.parse('June 6, 2020'), but it doesn't. (1591401600000 vs 1591423200000) – Vincent Jun 10 '20 at 00:03
  • php's strtotime and javascripts Date.parse are only similar at a basic level. As Ivan has commented above, strtotime is able to do far more by guessing the format and taking relative dates like 'tomorrow'. – Nigel Atkinson Nov 15 '21 at 04:16
  • I've updated the answer to remove the suggestion that this is somehow equivalent to `strtotime()`. There is no comparable functionality without an external library, which is why [this answer](https://stackoverflow.com/a/17606427/1255289) got my +1. – miken32 Mar 07 '22 at 18:52
55

I found this article and tried the tutorial. Basically, you can use the date constructor to parse a date, then write get the seconds from the getTime() method

var d=new Date("October 13, 1975 11:13:00");
document.write(d.getTime() + " milliseconds since 1970/01/01");

Does this work?

usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305
  • It seems that I does not work it the date is formatted in d.m.Y format. – Valentin Despa Feb 07 '13 at 09:44
  • 33
    -1. This only covers RFC 822 or ISO 8601 formatted dates, but `strtotime()` supports many other formats. – Ja͢ck May 20 '13 at 07:03
  • 1
    This may happen to satisfy the OP's use case, but it is a technically incorrect, invalid answer to the question. See (and please upvote) Westy92's answer. – Nate Abele Mar 07 '16 at 22:07
  • 1
    Just a quick note to be careful when using this built-in string parsing. Javascript will handle timezones differently for partial ISO date strings. The code `new Date('2021-04-01')` will have a time of midnight with a UTC timezone where as the date `new Date('04/01/2021')` will be created with a time of midnight in the local timezone. This difference can create subtle bugs in a program if you're parsing dates with both string formats. – Alana Storm Apr 26 '21 at 17:44
44

Check out this implementation of PHP's strtotime() in JavaScript!

I found that it works identically to PHP for everything that I threw at it.

Update: this function as per version 1.0.2 can't handle this case: '2007:07:20 20:52:45' (Note the : separator for year and month)

Update 2018:

This is now available as an npm module! Simply npm install locutus and then in your source:

var strtotime = require('locutus/php/datetime/strtotime');
Westy92
  • 19,087
  • 4
  • 72
  • 54
  • 5
    I don't normally like answers that are just links to libraries, but in this case since JavaScript doesn't handle nearly the crazy cases as strtotime so this is a fantastic answer. Thank you! – Fusty Mar 10 '17 at 00:40
  • Latest release of Locutus (7 Sep 2018 at this time) does not handle strings like 'yesterday 19:00'. – nicolas Mar 21 '19 at 17:30
5

I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.

// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();

Go back and forth using the subtract() and add() with the endOf() and startOf():

// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();
KhoPhi
  • 9,660
  • 17
  • 77
  • 128
1

Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

Try Moment.js - it provides cross-browser functionality for parsing dates:

var timestamp = moment("2013-02-08 09:30:26.123");
console.log(timestamp.milliseconds()); // return timestamp in milliseconds
console.log(timestamp.second()); // return timestamp in seconds
bedrin
  • 4,458
  • 32
  • 53
  • This does not fully answer the question (and has a negative score). Is there a way to revoke the bounty? – Westy92 Mar 08 '17 at 19:42
0

There are few modules that provides similar behavior, but not exactly like PHP's strtotime. Among few alternatives I found date-util yields the best results.

doc_id
  • 1,363
  • 13
  • 41
0

var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');
var date = moment(strdate).format('DD.MM.YYYY');
$("#result").text(date); //07.02.2017
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>

<div id="result"></div>
KingRider
  • 2,140
  • 25
  • 23
Limitless isa
  • 3,689
  • 36
  • 28
  • *Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js `Date()`* – sooo… same as `new Date(strdate)` really… – deceze Feb 06 '17 at 10:01
0

Maybe you can exploit a sample function like :

function strtotime(date, addTime){
  let generatedTime=date.getTime();
  if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds 
  if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes 
  if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours 
  return new Date(generatedTime);
}

let futureDate = strtotime(new Date(), {
    hours: 1, //Adding one hour
    minutes: 45 //Adding fourty five minutes
  });
document.body.innerHTML = futureDate;

`

Adnane Ar
  • 683
  • 7
  • 11
0

For those looking to convert the datetime to unix timestamp, you can do this using the Moment Library.

For Vue.js, you can do something like

let start = "2022/02/02 02:02:02";
return moment(start).format("x");
BlackPearl
  • 2,532
  • 3
  • 33
  • 49