Calculate difference between 2 timestamps using javascript

前端 未结 3 809
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 17:25

I have to calculate the difference between 2 timestamps. Also can you please help me with conversion of a string into timestamp. Using plain javascript only. NO JQUERY.

相关标签:
3条回答
  • 2020-12-14 17:29

    Based on the approved answer:

    function(timestamp1, timestamp2) {
        var difference = timestamp1 - timestamp2;
        var daysDifference = Math.floor(difference/1000/60/60/24);
    
        return daysDifference;
    }
    
    0 讨论(0)
  • 2020-12-14 17:33

    If your string is Mon May 27 11:46:15 IST 2013, you can convert it to a date object by parsing the bits (assuming 3 letter English names for months, adjust as required):

    // Convert string like Mon May 27 11:46:15 IST 2013 to date object 
    function stringToDate(s) {
      s = s.split(/[\s:]+/);
      var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5, 
                    'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11};
      return new Date(s[7], months[s[1].toLowerCase()], s[2], s[3], s[4], s[5]);
    }
    
    alert(stringToDate('Mon May 27 11:46:15 IST 2013'));
    

    Note that if you are using date strings in the same timezone, you can ignore the timezone for the sake of difference calculations. If they are in different timezones (including differences in daylight saving time), then you must take account of those differences.

    0 讨论(0)
  • 2020-12-14 17:47

    i am posting my own example try implement this in your code

    function timeDifference(date1,date2) {
        var difference = date1.getTime() - date2.getTime();
    
        var daysDifference = Math.floor(difference/1000/60/60/24);
        difference -= daysDifference*1000*60*60*24
    
        var hoursDifference = Math.floor(difference/1000/60/60);
        difference -= hoursDifference*1000*60*60
    
        var minutesDifference = Math.floor(difference/1000/60);
        difference -= minutesDifference*1000*60
    
        var secondsDifference = Math.floor(difference/1000);
    
        console.log('difference = ' + 
          daysDifference + ' day/s ' + 
          hoursDifference + ' hour/s ' + 
          minutesDifference + ' minute/s ' + 
          secondsDifference + ' second/s ');
    }
    
    0 讨论(0)
提交回复
热议问题