Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding seconds to a datetime variable in node.js

I have following code:

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

I want to get date after adding the seconds in the same format. Like:

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

How to get desired result?

like image 209
Tirthankar Kundu Avatar asked Jan 06 '14 07:01

Tirthankar Kundu


2 Answers

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())
}
like image 108
oconnecp Avatar answered Oct 21 '22 11:10

oconnecp


I would make use of the moment library for this. You could then achieve what you want as follows:

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);

This makes use of the moment #add() and #format().

like image 29
jabclab Avatar answered Oct 21 '22 11:10

jabclab