Check time difference in Javascript

后端 未结 18 1164
梦毁少年i
梦毁少年i 2020-11-22 04:27

How would you check time difference from two text-boxes in Javascript?

相关标签:
18条回答
  • 2020-11-22 04:45

    This function returns a string with the difference from a datetime string and the current datetime.

    function get_time_diff( datetime )
    {
        var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";
    
        var datetime = new Date( datetime ).getTime();
        var now = new Date().getTime();
    
        if( isNaN(datetime) )
        {
            return "";
        }
    
        console.log( datetime + " " + now);
    
        if (datetime < now) {
            var milisec_diff = now - datetime;
        }else{
            var milisec_diff = datetime - now;
        }
    
        var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
    
        var date_diff = new Date( milisec_diff );
    
        return days + " Days "+ date_diff.getHours() + " Hours " + date_diff.getMinutes() + " Minutes " + date_diff.getSeconds() + " Seconds";
    }
    

    Tested in the Google Chrome console (press F12)

    get_time_diff()
    1388534523123 1375877555722
    "146 Days 12 Hours 49 Minutes 27 Seconds"
    
    0 讨论(0)
  • 2020-11-22 04:46

    I have done some enhancements for timer counter

    //example return : 01:23:02:02
    //               : 1 Day 01:23:02:02
    //               : 2 Days 01:23:02:02 
    
    
    function get_timeDifference(strtdatetime) {
        var datetime = new Date(strtdatetime).getTime();
        var now = new Date().getTime();
    
        if (isNaN(datetime)) {
            return "";
        }
    
        //console.log(datetime + " " + now);
    
        if (datetime < now) {
            var milisec_diff = now - datetime;
        } else {
            var milisec_diff = datetime - now;
        }
    
        var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
    
        var date_diff = new Date(milisec_diff);
    
    
    
    
    
        var msec = milisec_diff;
        var hh = Math.floor(msec / 1000 / 60 / 60);
        msec -= hh * 1000 * 60 * 60;
        var mm = Math.floor(msec / 1000 / 60);
        msec -= mm * 1000 * 60;
        var ss = Math.floor(msec / 1000);
        msec -= ss * 1000
    
    
        var daylabel = "";
        if (days > 0) {
            var grammar = " ";
            if (days > 1) grammar = "s " 
            var hrreset = days * 24;
            hh = hh - hrreset;
            daylabel = days + " Day" + grammar ;
        }
    
    
        //  Format Hours
        var hourtext = '00';
        hourtext = String(hh);
        if (hourtext.length == 1) { hourtext = '0' + hourtext };
    
        //  Format Minutes
        var mintext = '00';
        mintext = String(mm); 
        if (mintext.length == 1) { mintext = '0' + mintext };
    
        //  Format Seconds
        var sectext = '00';
        sectext = String(ss); 
        if (sectext.length == 1) { sectext = '0' + sectext };
    
        var msectext = '00';
        msectext = String(msec);
        msectext = msectext.substring(0, 1);
        if (msectext.length == 1) { msectext = '0' + msectext };
    
        return daylabel + hourtext + ":" + mintext + ":" + sectext + ":" + msectext;
    }
    
    0 讨论(0)
  • 2020-11-22 04:49

    In my case, I'm gonna store the time in milliseconds on chrome storage and try to find diff in hours later.

    function timeDiffInHours(milliseconds){
        time_diff = (new Date).getTime() - milliseconds
        return parseInt((time_diff/(1000*60*60)) % 24)
    }
    
    // This is again sending current time and diff would be 0.
    timeDiffInHours((new Date).getTime());  
    
    0 讨论(0)
  • 2020-11-22 04:49

    You can set your custom difference by inserting values in end and updatedAt

    getDifference(theDate: string): string {
    let end = moment(moment(moment()).valueOf());
    let updatedAt = moment(new Date(theDate).valueOf());
    let diff = end.diff(updatedAt, "hour", false);
    if (diff > 8760) {
      diff = end.diff(updatedAt, "years", false);
      return diff > 1 ? diff + " years ago" : diff + " year ago";
    } else if (diff > 730) {
      diff = end.diff(updatedAt, "months", false);
      return diff > 1 ? diff + " months ago" : diff + " month ago";
    } else if (diff > 24) {
      diff = end.diff(updatedAt, "days", false);
      return diff > 1 ? diff + " days ago" : diff + " day ago";
    } else if (diff <= 0) {
      diff = end.diff(updatedAt, "minutes", false);
      return diff > 1 ? diff + " minutes ago" : diff + " minute ago";
    } else return diff > 1 ? diff + " hours ago" : diff + " hour ago";
    

    }

    0 讨论(0)
  • 2020-11-22 04:50
    var moment = require("moment");
    var momentDurationFormatSetup = require("moment-duration-format")
    
    var now  = "2015-07-16T16:33:39.113Z";
    var then = "2015-06-16T22:33:39.113Z";
    
    var ms = moment(now,"YYYY-MM-DD'T'HH:mm:ss:SSSZ").diff(moment(then,"YYYY-MM-DD'T'HH:mm:ss:SSSZ"));
    var d = moment.duration(ms);
    var s = d.format("dd:hh:mm:ss");
    console.log(s);
    
    0 讨论(0)
  • 2020-11-22 04:52

    Improvise. Subtract JavaScript Date objects to get their difference:

    // use a constant date (e.g. 2000-01-01) and the desired time to initialize two dates
    
    var date1 = new Date(2000, 0, 1,  9, 0); // 9:00 AM
    var date2 = new Date(2000, 0, 1, 17, 0); // 5:00 PM
    
    // the following is to handle cases where the times are on the opposite side of
    // midnight e.g. when you want to get the difference between 9:00 PM and 5:00 AM
    
    if (date2 < date1) {
        date2.setDate(date2.getDate() + 1);
    }
    
    var diff = date2 - date1;
    
    // 28800000 milliseconds (8 hours)
    

    You can then convert milliseconds to hour, minute and seconds like this:

    var msec = diff;
    var hh = Math.floor(msec / 1000 / 60 / 60);
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);
    msec -= mm * 1000 * 60;
    var ss = Math.floor(msec / 1000);
    msec -= ss * 1000;
    // diff = 28800000 => hh = 8, mm = 0, ss = 0, msec = 0
    

    You can convert time as string to 24-hour format like this:

    function parseTime(s) {
        var part = s.match(/(\d+):(\d+)(?: )?(am|pm)?/i);
        var hh = parseInt(part[1], 10);
        var mm = parseInt(part[2], 10);
        var ap = part[3] ? part[3].toUpperCase() : null;
        if (ap === "AM") {
            if (hh == 12) {
                hh = 0;
            }
        }
        if (ap === "PM") {
            if (hh != 12) {
                hh += 12;
            }
        }
        return { hh: hh, mm: mm };
    }
    parseTime("12:00 AM"); // {hh:  0, mm: 0}
    parseTime("12:00 PM"); // {hh: 12, mm: 0}
    parseTime("01:00 PM"); // {hh: 13, mm: 0}
    parseTime("23:00");    // {hh: 23, mm: 0}
    
    0 讨论(0)
提交回复
热议问题