jQuery: How to get the difference between two time and date with am/pm format

后端 未结 1 473
我寻月下人不归
我寻月下人不归 2021-01-26 09:32

I want to get the the difference between two time and date with am/pm format and get a 24 hour format result. for example: Given the time start 01/01/2007(mm/dd/yyyy) at 08:30:2

1条回答
  •  清酒与你
    2021-01-26 10:03

    From this site

    var timeStart = new Date("01/01/2007 " + "08:30:20 AM");
    var timeEnd = new Date("01/02/2007 " + "05:30:30 PM");
    
    
    function datediff(fromDate,toDate,interval) { 
      /*
                     * DateFormat month/day/year hh:mm:ss
                     * ex.
                     * datediff('01/01/2011 12:00:00','01/01/2011 13:30:00','seconds');
                     */
      
      var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7; 
      fromDate = new Date(fromDate); 
      toDate = new Date(toDate); 
      var timediff = toDate - fromDate; 
    
      if (isNaN(timediff)) return NaN; 
      switch (interval) { 
        case "years": return toDate.getFullYear() - fromDate.getFullYear(); 
        case "months": return ( 
          ( toDate.getFullYear() * 12 + toDate.getMonth() ) 
          - 
          ( fromDate.getFullYear() * 12 + fromDate.getMonth() ) 
        ); 
        case "weeks"  : return Math.floor(timediff / week); 
        case "days"   : return Math.floor(timediff / day);  
        case "hours"  : return Math.floor(timediff / hour);  
        case "minutes": return Math.floor(timediff / minute); 
        case "seconds": return Math.floor(timediff / second); 
        default: return undefined; 
      } 
    }
    
    
    $("#start").text(timeStart);
    $("#end").text(timeEnd);
    $("#diff").text(timeEnd - timeStart);
    $("#sec").text(datediff(timeStart, timeEnd, 'seconds') % 60);
    $("#min").text(datediff(timeStart, timeEnd, 'minutes') % 60);
    $("#hr").text(datediff(timeStart, timeEnd, 'hours'));
    div{
        background-color:yellow;
    }
    
    Time Start: 

    Time End:

    Difference:

    Seconds:

    Minutes:

    Hours:

    0 讨论(0)
提交回复
热议问题