Difference between Date.parse() and .getTime()

前端 未结 4 879
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 11:33

What\'s the main difference between:

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

and

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


        
4条回答
  •  -上瘾入骨i
    2021-01-04 11:55

    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()
    

提交回复
热议问题