Search code examples
javascriptdatedate-manipulation

How to get +15 minutes date time in Javascript with dd/mm/yyyy hh:ii AM/PM format?


I have to get +15 minutes date time in Javascript with dd/mm/yyyy hh:ii AM/PM format.

And I should compare two dates, which are in dd/mm/yyyy hh:ii AM/PM format.

JS:

var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12' 
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
var dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
var mm = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
var strTime = dd + '/' + mm + '/' + date.getFullYear() + " " + hours + ':' + minutes + ' ' + ampm;

Solution

  • let me first note that by default javascript would be giving you the time in UTC.

    A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time are the same as the UNIX epoch, which is the predominant base value for computer-recorded date and time values. (refer)

    The above is true when you use the Date() function to create a Date Object

    Using ES20xx, you can use a template literal (not supported in IE) and the padStart(not supported in IE) string extension to format the Date object to your liking as shown in the snippet below.

    I have also date.toLocaleString() which gives the string in a format that is commonly used in the region from where the browser is running the function

    The toLocaleString() method returns a string with a language sensitive representation of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.(refer)

    So the easy way to do this would be to add 15 minutes to the Unix timestamp obtained from the Date Object and formatting it with toLocaleString(this is the first snippet)

    You can also compare the two date objects below as you would any integer

    var dt1 = (new Date()).getTime();//Unix timestamp (in milliseconds)
    console.log("Current date Unix timestamp(ms)")
    console.log(dt1)
    console.log("15 mins later date Unix timestamp(ms)")
    console.log(dt1+900000)//15min=900000ms (15*60*1000)
    var dt = new Date(dt1);
    var dt2= new Date(dt1+900000)
    console.log("Unformatted dates 15 min apart (ISO 8601 / UTC)")
    console.log(dt)
    console.log(dt2)
    console.log("Formatted dates 15 min apart (According to your timezone)")
    console.log(dt.toLocaleString())
    console.log(dt2.toLocaleString())

    Below is the longer snippet that involves formatting the date object while displaying it. I feel this is not as optimal as the method above. But still does the job.

    var dt = new Date();
    console.log(dt);
    const localdte = dt.toLocaleString();
    console.log(localdte);
    const [dated, time, ampm] = localdte.split(' ');
    const [hh, mm, ss] = time.split(':');
    var date = `${
        dt.getDate().toString().padStart(2, '0')}/${
        (dt.getMonth()+1).toString().padStart(2, '0')}/${
        dt.getFullYear().toString().padStart(4, '0')} ${
        dt.getHours().toString().padStart(2, '0')}:${
        dt.getMinutes().toString().padStart(2, '0')}`
    console.log("Date right now");
    console.log(date);
    console.log("date 15 mins later");
    
    var date15 = `${
        dt.getDate().toString().padStart(2, '0')}/${
        (dt.getMonth()+1).toString().padStart(2, '0')}/${
        dt.getFullYear().toString().padStart(4, '0')} ${
        (dt.getMinutes()>44?(dt.hours==23?00:dt.getHours()+1):dt.getHours()).toString().padStart(2, '0')}:${
        ((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
    console.log("24 hour format " + date15);
    if (ampm == "PM" && hh != 12 && hh!=00) {
      var date15 = `${
        dt.getDate().toString().padStart(2, '0')}/${
        (dt.getMonth()+1).toString().padStart(2, '0')}/${
        dt.getFullYear().toString().padStart(4, '0')} ${
        (dt.getMinutes()>44?(dt.getHours()+1)%12:dt.getHours()%12).toString().padStart(2, '0')}:${
        ((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
      console.log("12 hour format " + date15 + ampm); //12 hour format
    } else if (hh == 00) {
      var date15 = `${
        dt.getDate().toString().padStart(2, '0')}/${
        (dt.getMonth()+1).toString().padStart(2, '0')}/${
        dt.getFullYear().toString().padStart(4, '0')} ${
        (dt.getMinutes()>44?1:12).toString().padStart(2, '0')}:${
        ((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
      console.log("12 hour format " + date15 + ampm);
    } else {
      console.log("12 hour format " + date15 + ampm); //12 hour format
    }
    const dateISO = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), ((dt.getMinutes() + 15) % 60), dt.getMilliseconds());
    console.log("ISO 8601 format (UTC)");
    console.log(dateISO);

    Note: there is a difference in the chrome console and the snippet console outputs. In the chrome console the output the date object is always formatted for local time. In the snippet console, the output of the date object is in UTC and ISO8601 compliant.

    Thanks to @RobG for pointing out the errors in my previous answer.