javascriptdatetimedatejs

How can I get the next time it's 14:00?


Is it possible to get the next time it's 14:00 (for example) as a Date object in Javascript using Datejs?

The documentation doesn't seem to show such an example and trying next 14:00 doesn't really seem to work.


Solution

  • You don't really need a library for this. You can create a Date object and if it's after 14:00, set the date to tomorrow, then set time to 14:00.

    Edit

    The original would allow any time from 14:00 to 14:59:59.999 as it only checked the hours. Updated so that any time from 14:00:00.001 to 23:59:59.999 is treated as after 14:00.

    Also added Date.js version (the documentation for which is minimal — perhaps there's something better).

    // Create a date for now and remember the time
    var d = new Date();
    var time = +d;
    
    // Set the time to 14:00 and, if earlier than now, add a day
    d.setHours(14,0,0,0);
    if ( d < time) {
      d.setDate(d.getDate() + 1);
    }
    
    document.write('Next 14:00: ' + d)

    Here is the Date.js version. I couldn't find a CDN to include as a snippet.

    // Equivalent using Date.js
    var d = Date.present();
    var t = +d;
    d.set({hour:14});
    if (d < t) {
      d.addDays(1);
    }
    
    document.write('<br>' + d3);
    

    Or, as one line:

    Date.today().set({hour:14}).isBefore(Date.present())? Date.today().addDays(1).set({hour:14}) : Date.today().set({hour:14});
    
    // Or
    Date.today().set({hour:14}).addDays(Date.today().set({hour:14}).isBefore(Date.present())? 1:0);
    

    I don't recommend the one liner versions; they're just there to show it can be done. They each create 3 date objects, whereas the other versions create only 1.