在node.js中向datetime变量添加秒数

时间:2014-01-06 07:53:14

标签: node.js datetime

我有以下代码:

var dbDate = '2013-11-15 12:51:18';
var seconds = 30;

我希望在以相同格式添加秒后获取日期。像:

var resultDate = dbDate + seconds; //'2013-11-15 12:51:48'

如何获得理想的结果?

3 个答案:

答案 0 :(得分:12)

var dbDate = '2013-11-15 12:51:18';
var seconds = 30;


var parsedDate = new Date(Date.parse(dbDate))
var newDate = new Date(parsedDate.getTime() + (1000 * seconds))


console.log(formatDate(newDate))


function formatDate(date){
    return ('{0}-{1}-{3} {4}:{5}:{6}').replace('{0}', date.getFullYear()).replace('{1}', date.getMonth() + 1).replace('{3}', date.getDate()).replace('{4}', date.getHours()).replace('{5}', date.getMinutes()).replace('{6}', date.getSeconds())
}

答案 1 :(得分:2)

为此,我会使用moment库。然后,您可以按照以下方式实现您想要的目标:

var moment = require('moment');

var dateFormat = 'YYYY-MM-DD HH:mm:ss';

var dbDate = '2013-11-15 12:51:18';
var seconds = 30;
var resultDate = moment(dbDate).add('seconds', seconds).format(dateFormat);

这可以使用moment #add()#format()

答案 2 :(得分:1)

另一种方法:

var a;
/// create our date from our nicely formatted Y-m-d H:i:s string
a = new Date('2013-11-15 12:51:18');
/// add 30 seconds
a = new Date(a.getTime() + (30 * 1000));
/// use toISOString, it's the closest to Y-m-d H:i:s
a = a.toISOString();
/// modify ISO string to get Y-m-d H:i:s
a = a.split('.')[0].replace('T', ' ');
/// output!
console.log( a );