2010-10-29 189 views
64

在PHP中,您可以使用strtotime()轻松地将英文文本日期时间描述转换为适当的日期。Javascript的等效PHP的strtotime()?

Javascript中有没有类似的东西?

+0

对于从格式DD.MM.YYYY解析,检查http://stackoverflow.com/questions/1576753/parse-datetime-string-in-javascript – 2013-02-07 09:52:18

回答

41

我发现this article并试过本教程。基本上,你可以使用日期构造解析的日期,然后写从getTime()方法

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

请问这项工作得到秒?

+0

看来我不起作用,日期格式为dmY格式。 – 2013-02-07 09:44:20

+22

-1。这只包括RFC 822或ISO 8601格式的日期,但'strtotime()'支持许多其他格式。 – 2013-05-20 07:03:45

+1

这可能会发生在满足OP的用例上,但这是一个技术上不正确,无法回答的问题。见(并请upvote)Westy92的答案。 – 2016-03-07 22:07:34

53

是的。并且在所有主要的浏览器支持:

var ts = Date.parse("date string"); 

唯一不同的是,这个函数返回毫秒,而不是秒,所以你需要通过1000

Check what valid formats can JavaScript parse.

+1

这应该是被接受的答案。 +1 – Doorknob 2013-07-12 02:47:46

+18

不是;这与php strtotime非常不同,没有一个php文档工作的例子,没有一个'strtotime(“now”); strtotime(“2000年9月10日”); strtotime(“+ 1 day”); strtotime(“+ 1 week”); strtotime(“+ 1周2天4小时2秒”); strtotime(“下周四”); strtotime(“上周一”);' – 2014-01-04 00:47:48

+0

谢谢@Arnaldo。这对我有用。你的答案比“Djechelon's”更可接受 – Adi 2015-01-26 12:19:31

21

退房划分结果this在JavaScript中实现PHP的strtotime()!

我发现它对PHP所做的所有操作都一样。

更新:此功能按1.0.2版本无法处理这种情况:'2007:07:20 20:52:45' (注意:分离的年份和月份)

更新2018:

这是现在可作为npm模块使用!只要npm install locutus,然后在您的源:

var strtotime = require('locutus/php/datetime/strtotime'); 
+1

我通常不喜欢只是链接到图书馆的答案,但在这种情况下,因为JavaScript并没有将几乎疯狂的情况作为strtotime处理,所以这是一个很好的答案。 谢谢! – user819644 2017-03-10 00:40:44

4

我嫉妒在PHP的strtotime(),但我用的时刻做我在JavaScript。不像从PHP那样甜蜜,但也巧妙地做到了这一点。

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

来回走使用subtract()add()endOf()startOf()

// last day of previous month 
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate(); 
-2

对于解析字符串is inconsistent浏览器支持。由于没有关于哪种格式应该被支持的规范,所以某些浏览器中的工作方式在其他浏览器中不起作用。

尝试Moment.js - 它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 
+0

这并没有完全回答这个问题(并且有一个负分)。有没有办法撤销赏金? – Westy92 2017-03-08 19:42:11

0

有迹象表明,提供类似的行为几个模块,但不完全像PHP的的strtotime。在我发现的几个替代品中,date-util可以产生最好的结果。

-1

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>

+0

*弃用警告:提供的值不是采用可识别的ISO格式。瞬间建设回落到js Date()'* - sooo ...与'new Date(strdate)'一样真的...... – deceze 2017-02-06 10:01:54