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\"
Does this help?
function getDateString(addT){
var time = new Date();
time.setHours(time.getHours() + addT );
return ((time.getHours()<10)?"0":"")+time.getHours() + ':' + time.getMinutes();
}
Then just use it pop out the data on the graph where you want?
ie:
for (i=0;i<=24;i+=6){
yourbox.innerHTML = '<p>'+getDateString(i)+'</p>';
}
or somesuch;
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>
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);
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.
I like to do this like that
new Date(new Date().setHours(new Date().getHours() + 6))
or
new Date(new Date().setHours(new Date().getHours() + 6)).toString()