简体   繁体   English

如何在JS中比较时间

[英]How to compare time in JS

How can compare two variables in JS with value as time string in the below format 如何使用以下格式将JS中的两个变量的值作为时间字符串进行比较

Mon, 29 Feb 2016 09:09:53 GMT
Thu, 21 Jan 2016 05:08:46 GMT

Simply doing x > y will work ??? 简单地做x> y就可以了??? Or Do I need to convert into other format.. 还是我需要转换成其他格式?

strtotime()

above function is available in php which will parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC). 上面的函数在php中可用,它将解析该格式为Unix时间戳(自1970年1月1日00:00:00 UTC以来的秒数)。

Is there any function to do the same in JS ?? 在JS中有什么功能可以做同样的事情吗?

 Date.parse('Mon, 29 Feb 2016 09:09:53 GMT') > Date.parse('Thu, 21 Jan 2016 05:08:46 GMT')

真正

In Javascript, you should compare Date objects: 在Javascript中,您应该比较Date对象:

var foo = new Date("Mon, 29 Feb 2016 09:09:53 GMT");
var bar = new Date("Thu, 21 Jan 2016 05:08:46 GMT");

if(foo > bar) { ... }

There are multiple ways of creating an instance of the Date object. 有多种创建Date对象实例的方法。 You can read more about it on MDN . 您可以在MDN上阅读有关它的更多信息。

Storing the time string in a variable: 将时间字符串存储在变量中:

var foo = "Mon, 29 Feb 2016 09:09:53 GMT";
var bar = new Date(foo);

I got it. 我知道了。
getTime() returns the number of milliseconds since January 1, 1970: getTime()返回自1970年1月1日以来的毫秒数:

<script>
var d = new Date();
var time = d.getTime();
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM