Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中减去日期/时间? [重复](How to subtract date/time in JavaScript? [duplicate])

This question already has an answer here:(这个问题在这里已有答案:)

How do I get the difference between two Dates in JavaScript?(如何在JavaScript中获得两个日期之间的差异?) 16 answers(16个答案)

I have a field at a grid containing date/time and I need to know the difference between that and the current date/time.(我在包含日期/时间的网格中有一个字段,我需要知道它与当前日期/时间之间的区别。)

What could be the best way of doing so?(这可能是最好的方法吗?) The dates are stored like "2011-02-07 15:13:06" .(日期存储如"2011-02-07 15:13:06" 。)   ask by Ahmad Farid translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will give you the difference between two dates, in milliseconds(这将为您提供两个日期之间的差异,以毫秒为单位)

var diff = Math.abs(date1 - date2); In your example, it'd be(在你的例子中,它是) var diff = Math.abs(new Date() - compareDate); You need to make sure that compareDate is a valid Date object.(您需要确保compareDate是一个有效的Date对象。) Something like this will probably work for you(这样的事可能对你有用) var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/'))); ie turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06') , which is a format the Date constructor can comprehend.("2011-02-07 15:13:06"转换为new Date('2011/02/07 15:13:06') ,这是Date构造函数可以理解的格式。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...