从JSON日期字符串计算日期差异

时间:2015-09-08 20:54:46

标签: javascript json

我将日期存储在timesheet.json中,格式为:

[{"id":1,"note":"some note about task 1","start":"2015-08-28 02:41:02
    +0200","end":"2015-08-28 02:58:58 +0200","sheet":"job"},{"id":2,"note":"some
    note about task 2","start":"2015-09-03 03:15:04 +0200","end":"2015-09-03
    03:57:34 +0200","sheet":"job"},{"id":3,"note":"some note about task
    3","start":"2015-09-03 23:09:50 +0200","end":"2015-09-03 23:58:00
    +0200","sheet":"job"},{"id":5,"note":"this is a test task","start":"2015-09-08
    19:46:19 +0200","end":"2015-09-08 20:11:22 +0200","sheet":"job"}]

因为我本身并没有在json中导出差异,我正在尝试 自己计算,并在发送之前将其附加到最初解析的json handlebars.js用于模板渲染。

但是我无法将上述字符串表示转换为Date() 对象,能够对时差进行计算。

这种结构适用于node cli,我可以做startTime.getTime()但是。{ 它不适用于javascript:

    var startTime = new Date('2015-08-28 02:58:58 +0200');

以下代码不起作用:

    $.getJSON('./timesheet.json', function(data){

        context.tasks = data;

        for (var prop in context.tasks){

            var startTime = new Date(context.tasks[prop].start);

            console.log(startTime); // Invalid Date
            console.log(context.tasks[prop].start); // 2015-08-28 02:41:02 +0200

            var endTime = new Date(context.tasks[prop].end);

            var diff = endTime.getTime() - startTime.getTime(); // this doesn't work as endTime and startTime are not Date objects!
            cosole.log(diff); // yields NaN
        }
        var html = template(context);

        $('.tasklist').append(html);
    });

4 个答案:

答案 0 :(得分:0)

我建议您使用moment.js。然后您的代码变为以下内容。我添加了一些使用moment.js持续时间api的例子,这通常是查看日期差异的更好方法。

$.getJSON('./timesheet.json', function(data) {
    for (var i = 0; i < data.length; i++) {
        var startTime = moment(data[i].start);
        var endTime = moment(data[i].end);

        var diff = endTime.diff(startTime); // Difference in milliseconds
        console.log(diff);

        var duration = moment.duration(diff); // Duration object which may be more useful to you
        console.log('as days: ' + duration.asDays());
        console.log('as minutes: ' + duration.asMinutes());
        // Etc...
    }
});

答案 1 :(得分:0)

我不确定你的json是如何格式化的。但是,我认为您正在错误地访问您的json。我尝试了以下代码,产生了正确的结果。

确保使用for循环代替for..in

var timesheetJson = [{
    'start': '2015-08-28 02:41:02 +0200',
    'end': '2015-08-28 02:58:58 +0200'
}, {
    'start': '2015-09-03 03:15:04 +0200',
    'end': '2015-09-03 03:57:34 +0200'
}];

for (var i=0; i<timesheetJson.length; i++) {

    var startTime = new Date(timesheetJson[i].start);
    var endTime = new Date(timesheetJson[i].end);

    var diff = endTime.getTime() - startTime.getTime();
    console.log(diff); 
}

答案 2 :(得分:0)

您需要检查来自JSON文件的数据。实际日期操作代码没有任何问题。

当你使它工作时,这会将你的结果以毫秒转换为浮点天:

diff / 1000 / 60 / 60 / 24

您可以使用公式的每个步骤和mod %表达式以更易读的格式返回:

var seconds = diff / 1000 % 60

var minutes = diff / 1000 / 60 % 60

var hours = diff / 1000 / 60 / 60 % 24

...

答案 3 :(得分:0)

您正在从数据库获取UTC格式的时间戳,而javascript并不“理解”它如何处理它。
我们必须通过将其拆分为零件并获得年,月,日,小时,分钟,秒,时区参数并从中创建日期对象来重建它。

所以这是解决方案:

function UTCToDateObject(utcString) {
    var t = utcString.split(/[- :]/);
    var year = t[0];
    var month = t[1]-1;
    var day = t[2];
    var hours = t[3] || 0;
    var minutes = t[4] || 0;
    var seconds = t[5] || 0;

    if(t[6]) { // if timezone parameter exist, we cut hours and minutes to get to +0000
        var hours =+ (-1)*parseInt(t[6].substr(0,3));
        var minutes =+ (-1)*parseInt(t[6].substr(3));
    }

    var utcTime = Date.UTC(year, month, day, hours, minutes, seconds); // generating UTC time from parameters
    return new Date(utcTime); // return date object
}

function UTCToTime(utc_string) {
    return UTCToDateObject(utc_string).getTime()/1000;
}

function dateDiffUTC(startTime, endTime) {
    return UTCToTime(endTime) - UTCToTime(startTime);
}


$.getJSON('./timesheet.json', function(data){
    context.tasks = data;
    for (var prop in context.tasks){
        var startTime = context.tasks[prop].start;
        var endTime = context.tasks[prop].end;
        var diff = dateDiffUTC(startTime, endTime);
        context.tasks[prop].timeDiff = diff;
        console.log(diff);
    }
    var html = template(context);

    $('.tasklist').append(html);
});