我使用moment.js来格式化我的日期时间,这里我有两个日期值,当一个日期大于另一个时,我想实现一个特定的函数。我读了他们的大部分文档,但没有找到实现这个功能的函数。我知道它会在那里。
这是我的代码:
var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
var d = moment(date_time).tz('UTC'); // first date
var now = new Date(),
dnow = moment(now).tz('UTC'),
snow = dnow.minute() % 15,
diffnow = 15 - snow,
tonow = moment(dnow).add('minute', diffnow),
ahead30now = moment(tonow).add('minute', 30);
if (d > ahead30now) {
// allow input time
console.log('UTC TIME DB', d.format());
} else {
}
编辑
var date_time = req.body.date + 'T' + req.body.time + req.body.timezone; // 2014-03-24T01:15:000
var utc_input_time = moment(date_time).utc(); // 2014-03-24T01:15:000
console.log('utc converted date_time', moment(date_time).utc().format("YYYY-MM-DDTHH:mm:SSS"));
var isafter = moment(utc_input_time).isAfter(moment('2014-03-24T01:14:000')); // true
if(isafter === true){
console.log('is after true');
} else {
console.log('is after is false');
}
在这里,我比较了两个日期,即2014-03-24T01:15:000 > 2014-03-24T01:14:000,期望第一个比第二个大,但它总是走向else条件。我不知道为什么?
Jsfiddle: http://jsfiddle.net/guhokemk/1/
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA,"DD/MM/YYYY");
var momentB = moment(dateTimeB,"DD/MM/YYYY");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("11/07/2015", "10/07/2015"));
如果dateTimeA大于dateTimeB,该方法返回1
如果dateTimeA等于dateTimeB,则该方法返回0
如果dateTimeA小于dateTimeB,该方法返回-1
我相信您正在寻找查询功能,isBefore, isSame, isAfter。
但要确切地说出你在尝试什么有点困难。也许你只是想知道输入时间和当前时间之间的差异?如果是,考虑差分函数diff。例如:
moment().diff(date_time, 'minutes')
其他一些事情:
There's an error in the first line:
var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
That's not going to work. I think you meant:
var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
Of course, you might as well:
var date_time = '2013-03-24T10:15:20:12Z';
You're using: .tz('UTC') incorrectly. .tz belongs to moment-timezone. You don't need to use that unless you're working with other time zones, like America/Los_Angeles.
If you want to parse a value as UTC, then use:
moment.utc(theStringToParse)
Or, if you want to parse a local value and convert it to UTC, then use:
moment(theStringToParse).utc()
Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.
You seem to be getting the "now" instance by moment(new Date()). You can instead just use moment().
更新
根据你的编辑,我认为你可以这样做:
var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');
或者,如果你想确保你的字段被验证为正确的格式:
var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');