如何在 JavaScript 中减去日期/时间? [英] How to subtract date/time in JavaScript?

查看:21
本文介绍了如何在 JavaScript 中减去日期/时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在包含日期/时间的网格中有一个字段,我需要知道它与当前日期/时间之间的区别.这样做的最佳方法是什么?

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?

日期的存储方式为 "2011-02-07 15:13:06".

推荐答案

这会给你两个日期之间的差异,以毫秒为单位

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

在你的例子中,它会是

var diff = Math.abs(new Date() - compareDate);

您需要确保 compareDate 是一个有效的 Date 对象.

You need to make sure that compareDate is a valid Date object.

这样的东西可能对你有用

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

即将 "2011-02-07 15:13:06" 转化为 new Date('2011/02/07 15:13:06'),这是一种格式Date 构造函数可以理解.

i.e. 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.

这篇关于如何在 JavaScript 中减去日期/时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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