Date.parse()和.getTime()之间的区别 [英] Difference between Date.parse() and .getTime()

查看:792
本文介绍了Date.parse()和.getTime()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  dt = new Date(); 
ms = Date.parse(dt);

  dt = new Date(); 
ms = dt.getTime();

他们有相同的输出,但有什么区别?我应该使用哪一个?

解决方案

第一个版本转换一个 Date 到一个字符串并解析它,这是一个非常无意义的事情 - 在某些情况下可能会丢失信息,我怀疑。 (想象一下在DST转换期间,当时钟恢复时 - 同一个本地时间出现两小时,而且我不知道这个字符串表示是否会在两次出现之间区分。)



第二个在我看来很明显。一般来说,当您不需要字符串转换时,您应该避免使用字符串转换 - 它们经常会导致问题,而您正在尝试执行的任何内容都不是关于字符串表示形式。 / p>

除非你真的需要其他地方的 Date ,使用起来会更简单: / p>

  ms = new Date()。getTime()

或者更好的是,使用静态 now() 方法:

  ms = Date.now()


What's the main difference between:

dt = new Date();
ms = Date.parse(dt);

and

dt = new Date();
ms = dt.getTime();

they have the same output, but what the difference? and which one should i use?

解决方案

The first version converts a Date to a string and parses it, which is a pretty pointless thing to do - and in some cases could lose information, I suspect. (Imagine during a DST transition, when the clock goes back - the same local times occur twice for that hour, and I don't know offhand whether the string representation would differentiate between the two occurrences.)

The second is significantly cleaner in my view. In general, you should avoid string conversions when you don't need them - they can often lead to problems, and there's nothing in what you're trying to do which is inherently about a string representation.

Unless you actually need the Date elsewhere, it would be simpler to use:

ms = new Date().getTime()

Or even better, use the static now() method:

ms = Date.now()

这篇关于Date.parse()和.getTime()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆