Add 6 hours to current time and display to page

后端 未结 5 1071
执笔经年
执笔经年 2020-12-10 01:40

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\"

相关标签:
5条回答
  • 2020-12-10 01:51

    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;

    0 讨论(0)
  • 2020-12-10 02:01

    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>
    
    0 讨论(0)
  • 2020-12-10 02:06

    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);
    
    0 讨论(0)
  • 2020-12-10 02:13
    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.

    0 讨论(0)
  • 2020-12-10 02:15

    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()
    
    0 讨论(0)
提交回复
热议问题