Parse.com:查询日期和UTC

Parse.com: query with date and UTC

本文关键字:UTC 日期 查询 com Parse      更新时间:2023-10-26

我想根据日期字段删除对象。

目前,我用以下代码成功删除了超过1天的事件:

function deleteOldEvents() {
    var today = new Date();
    var days = 1;
    var time = (days * 24 * 3600 * 1000);
    var expirationDate = new Date(today.getTime() - (time));
    var query = new Parse.Query('Events');
        // All events have more than 1 days
        query.lessThan('date', expirationDate);
        query.find().then(function (Events) {
            Parse.Object.destroyAll(Events, {
                success: function(success) {}, error: function(error) {}
            });
    });
}

但现在,我想删除超过12小时的事件:

function deleteOldEvents() {
    var today = new Date();
    var time = (12 * 3600 * 1000);
    var expirationDate = new Date(today.getTime() - (time));
    var query = new Parse.Query('Events');
        // All events have more than 12 hours
        query.lessThan('date', expirationDate);
        query.find().then(function (Events) {
            Parse.Object.destroyAll(Events, {
                success: function(success) {}, error: function(error) {}
            });
    });
}

此代码删除超过14小时而不是12小时的事件。。。也许我必须使用UTC?我在法国(UTC+2),这可能就是为什么删除事件超过14小时,而不是12小时的原因?

如何在javascript中使用UTC?

您的代码工作正常,您对UTC问题的看法是正确的-Date.getTime()返回自1970年1月1日以来的UTC时间毫秒数。对于与UTC时区不同的国家/地区,您需要加入偏移。

使用Date.getTimezoneOffset()校正UTC差异:

// getTimezoneoffset returns offset in minutes, so converting to milliseconds...
var offset = today.getTimezoneOffset()*60*1000;
var expirationDate = new Date(today.getTime() - (time) + (offset));