Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS add two hours to date?

Tags:

node.js

I've got a date string as such:

Tue Jul 29 2014 23:44:06 GMT+0000 (UTC)

How can I add two hours to this?

So I get:

Tue Jul 29 2014 01:44:06 GMT+0000 (UTC)

like image 745
user3490755 Avatar asked Jul 29 '14 23:07

user3490755


People also ask

How do I add 24 hours to a Unix timestamp in JavaScript?

This code will returns new unix time after adding 24hrs in current unix timestamp. $currentUnixTime=time(); $newUnixTime=strtotime('+1 day', $currentUnixTime); return newUnixTime; javascript.

How do you add minutes to a Date?

To add the number of minutes into the Date object using the setMinutes() method first we get the value of minutes of the current time using the getMinutes( ) method and then add the desired number of minutes into it and pass the added value to the setMinutes( ) method.

How do you display the current Date in JavaScript?

In JavaScript, we can easily get the current date or time by using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.


2 Answers

Here's one solution:

var date = new Date('Tue Jul 29 2014 23:44:06 GMT+0000 (UTC)').getTime();
date += (2 * 60 * 60 * 1000);
console.log(new Date(date).toUTCString());
// displays: Wed, 30 Jul 2014 01:44:06 GMT

Obviously once you have the (new) date object, you can format the output to your liking if the native Date functions do not give you what you need.

like image 91
mscdex Avatar answered Sep 28 '22 19:09

mscdex


Using MomentJS:

var moment = require('moment');

var date1 = moment("Tue Jul 29 2014 23:44:06 GMT+0000 (UTC)");

//sets an internal flag on the moment object.
date1.utc();

console.log(date1.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ (UTC)"));

//adds 2 hours
date1.add(2, 'h');

console.log(date1.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ (UTC)")); 

Prints out the following:

Tue Jul 29 2014 23:44:06 GMT+0000 (UTC)

Wed Jul 30 2014 01:44:06 GMT+0000 (UTC)

like image 33
Piotr Tomasik Avatar answered Sep 28 '22 18:09

Piotr Tomasik