简体   繁体   English

使用Moment.js,如何将时刻转换为日期或进行日历日期比较?

[英]Using Moment.js, how do you convert a moment to a date or do calendar date comparisons?

If you have a moment which is a datetime. 如果您有一刻是约会时间。

var d1 = moment();

How do I convert d1 to a date (losing time) so you can do math. 如何将d1转换为date (丢失时间),以便可以进行数学运算。 I'd like to do.. 我想做..

var d1 = moment(); // convert this to a date.
var d2 = moment(); // convert this to a date.

These should return like this*; 这些应该像这样返回*;

d1.isBefore(d2) // false;
d1.isAfter(d2) // false;
d1.isSame(d2) // true

Footnotes 脚注

* assuming d2 didn't occur after the day-rollover

Try 尝试

moment().startOf('day')

That will shift the time to midnight (in most cases). 在大多数情况下,这会将时间更改为午夜。

Using the two argument form of momement.js comparisons 使用momement.js比较的两个参数形式

I'm not sure of the easiest way to do this in that fashion, but the comparison methods are smarter than that.. This is why the .valueOf overrides weren't sufficient for the library. 我不确定以这种方式执行此操作的最简单方法,但是比较方法比这更聪明。这就是为什么.valueOf重写不足以实现该库的原因。

d1.isBefore(d2); // same as d1 < d2;

But, the signature is 但是,签名是

moment().isBefore(Moment|String|Number|Date|Array, String);

And, the second String argument corresponds to this 并且,第二个String参数与此对应

Like moment#isAfter and moment#isSame, any of the units of time that are supported for moment#startOf are supported for moment#isBefore. 与moment#isAfter和moment#isSame一样,moment#isBefore支持moment#startOf支持的任何时间单位。 Year, month, week, day, hour, minute, and second. 年,月,周,日,小时,分钟和秒。

So simply run the same tests like this.. 因此,只需像这样运行相同的测试即可。

d1.isBefore(d2, 'day') // false;
d1.isAfter(d2, 'day')  // false;
d1.isSame(d2, 'day')   // true

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

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