Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 6 hours to current time and display to page

So, I'm trying to add some labels to a graph, and I want to add them to 6, 12, 18, and 24 hours on the horizontal axis.

I want to write these times in a "hh:mm" format (23:10, 05:10, 11:10, and 17:10 for example) for the local (computer) timezone?

Can someone help me with this?

like image 482
A_Elric Avatar asked Oct 23 '12 15:10

A_Elric


People also ask

How do you add hours to current date and time?

To add hours in the current date-time, we use AddHours() method of DateTime class in C#. Syntax: DateTime DateTime. AddHours(double);

How to add hours in current time in JavaScript?

function addHours(numOfHours, date = new Date()) { date. setTime(date. getTime() + numOfHours * 60 * 60 * 1000); return date; } // 👇️ Add 1 hour to current date const result = addHours(1); // 👇️ Add 2 hours to another date const date = new Date('2022-03-14T09:25:30.820'); // 👇️ Mon Mar 14 2022 11:25:30 console.

How to add hours and minutes to date in JavaScript?

To add hours and minutes to a date, use the setHours() and setMinutes() method in JavaScript.


3 Answers

based on How to add 30 minutes to a JavaScript Date object?

var d1 = new Date ();
var d2 = new Date ( d1 );
d2.setHours ( d1.getHours() + 6 );

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date will show how to manipulate Date objects.

added your code with some fixes. edited to add second document.write

<script type="text/javascript"> 
var timer = 24; 
var d1 = new Date(); 
var d2 = new Date();
d1.setHours(+d2.getHours()+(timer/4) ); 
d1.setMinutes(new Date().getMinutes()); 
document.write(d1.toTimeString("hh:mm"));
document.write(d1.getHours()+":"+d1.getMinutes());
</script>
like image 126
Pedro del Sol Avatar answered Oct 20 '22 15:10

Pedro del Sol


try this

var today = new Date();
alert(today);
today.setHours(today.getHours()+6);
alert(today);
today.setHours(today.getHours()+6);
alert(today);
today.setHours(today.getHours()+6);
alert(today);
today.setHours(today.getHours()+6);
alert(today);
like image 9
Ramesh Kotha Avatar answered Oct 20 '22 15:10

Ramesh Kotha


var MILLISECS_PER_HOUR = 60 /* min/hour */ * 60 /* sec/min */ * 1000 /* ms/s */;

function sixHoursLater(d) {
  return new Date(+d + 6*MILLISECS_PER_HOUR);
}

The numeric value of a date is milliseconds per epoch, so you can just add a number of milliseconds to it to get an updated numeric value.

The + prefix operator converts the date to its numeric value.

like image 4
Mike Samuel Avatar answered Oct 20 '22 14:10

Mike Samuel