web-dev-qa-db-fra.com

Vérifier le décalage horaire en Javascript

Comment vérifier la différence de temps entre deux zones de texte en Javascript?

88
Kishh

Improviser. Soustrayez JavaScript Date objets pour obtenir leur différence:

// 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)

Vous pouvez ensuite convertir les millisecondes en heures, minutes et secondes comme ceci:

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

Vous pouvez convertir l'heure sous forme de chaîne au format 24 heures comme ceci:

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}
149
Salman A

Cette fonction retourne une chaîne avec la différence d'une chaîne datetime et de la date/heure actuelle.

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";
}

Testé dans Google Chrome console (appuyez sur F12)

get_time_diff()
1388534523123 1375877555722
"146 Days 12 Hours 49 Minutes 27 Seconds"
17
The Demz

Voici la solution qui a fonctionné pour moi:

var date1 = new Date("08/05/2015 23:41:20");
var date2 = new Date("08/06/2015 02:56:32");

var diff = date2.getTime() - date1.getTime();

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;

alert(hh + ":" + mm + ":" + ss);
10
FredFury

Voici ma traduction ....

function get_time_difference(earlierDate, laterDate) 
{
    var oDiff = new Object();

    //  Calculate Differences
    //  -------------------------------------------------------------------  //
    var nTotalDiff = laterDate.getTime() - earlierDate.getTime();

    oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
    nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;

    oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
    nTotalDiff -= oDiff.hours * 1000 * 60 * 60;

    oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
    nTotalDiff -= oDiff.minutes * 1000 * 60;

    oDiff.seconds = Math.floor(nTotalDiff / 1000);
    //  -------------------------------------------------------------------  //

    //  Format Duration
    //  -------------------------------------------------------------------  //
    //  Format Hours
    var hourtext = '00';
    if (oDiff.days > 0){ hourtext = String(oDiff.days);}
    if (hourtext.length == 1){hourtext = '0' + hourtext};

    //  Format Minutes
    var mintext = '00';
    if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
    if (mintext.length == 1) { mintext = '0' + mintext };

    //  Format Seconds
    var sectext = '00';
    if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
    if (sectext.length == 1) { sectext = '0' + sectext };

    //  Set Duration
    var sDuration = hourtext + ':' + mintext + ':' + sectext;
    oDiff.duration = sDuration;
    //  -------------------------------------------------------------------  //

    return oDiff;
}
6
dmd733

Une bonne solution est disponible à 

http://blogs.digitss.com/javascript/calculate-datetime-difference-simple-javascript-code-snippet/

donne la sortie dans le format de votre choix differnece de 

jours: heures: minutes: secondes. 

Une version légèrement modifiée de ce code est présentée ci-dessous.

 var vdaysdiff; // difference of the dates
   var vhourDiff;
   var vmindiff;
   var vsecdiff;

   vdaysdiff = Math.floor(diff/1000/60/60/24);  // in days
   diff -= vdaysdiff*1000*60*60*24;

   vhourDiff = Math.floor(diff/1000/60/60);  // in hours
   diff -= vhourDiff*1000*60*60;

   vmindiff = Math.floor(diff/1000/60); // in minutes
   diff -= vmindiff*1000*60;

   vsecdiff= Math.floor(diff/1000);  // in seconds

   //Text formatting
   var hourtext = '00';
   if (hourDiff > 0){ hourtext = String(hourDiff);}
   if (hourtext.length == 1){hourtext = '0' + hourtext};                                                              

   var mintext = '00';                           
   if (mindiff > 0){ mintext = String(mindiff);}
   if (mintext.length == 1){mintext = '0' + mintext};

  //shows output as HH:MM ( i needed shorter duration)
   duration.value= hourtext + ':' + mintext;
5
Ram

Le diff de temps en millisecondes

firstDate.getTime() - secondDate.getTime() 
3
levi

Ceci est un ajout à la réponse de dmd733 . J'ai corrigé le bogue avec la durée de la journée (enfin, j'espère l'avoir fait, je n'ai pas pu tester tous les cas). 

J'ai aussi rapidement ajouté une propriété String au résultat contenant le temps général écoulé (désolé pour les si imbriqués! !!). Par exemple, si utilisé pour l'interface utilisateur et indiquant quand quelque chose a été mis à jour (comme un flux RSS). Sorte de lieu mais agréable à avoir:

function getTimeDiffAndPrettyText(oDatePublished) {

  var oResult = {};

  var oToday = new Date();

  var nDiff = oToday.getTime() - oDatePublished.getTime();

  // Get diff in days
  oResult.days = Math.floor(nDiff / 1000 / 60 / 60 / 24);
  nDiff -= oResult.days * 1000 * 60 * 60 * 24;

  // Get diff in hours
  oResult.hours = Math.floor(nDiff / 1000 / 60 / 60);
  nDiff -= oResult.hours * 1000 * 60 * 60;

  // Get diff in minutes
  oResult.minutes = Math.floor(nDiff / 1000 / 60);
  nDiff -= oResult.minutes * 1000 * 60;

  // Get diff in seconds
  oResult.seconds = Math.floor(nDiff / 1000);

  // Render the diffs into friendly duration string

  // Days
  var sDays = '00';
  if (oResult.days > 0) {
      sDays = String(oResult.days);
  }
  if (sDays.length === 1) {
      sDays = '0' + sDays;
  }

  // Format Hours
  var sHour = '00';
  if (oResult.hours > 0) {
      sHour = String(oResult.hours);
  }
  if (sHour.length === 1) {
      sHour = '0' + sHour;
  }

  //  Format Minutes
  var sMins = '00';
  if (oResult.minutes > 0) {
      sMins = String(oResult.minutes);
  }
  if (sMins.length === 1) {
      sMins = '0' + sMins;
  }

  //  Format Seconds
  var sSecs = '00';
  if (oResult.seconds > 0) {
      sSecs = String(oResult.seconds);
  }
  if (sSecs.length === 1) {
      sSecs = '0' + sSecs;
  }

  //  Set Duration
  var sDuration = sDays + ':' + sHour + ':' + sMins + ':' + sSecs;
  oResult.duration = sDuration;

  // Set friendly text for printing
  if(oResult.days === 0) {

      if(oResult.hours === 0) {

          if(oResult.minutes === 0) {
              var sSecHolder = oResult.seconds > 1 ? 'Seconds' : 'Second';
              oResult.friendlyNiceText = oResult.seconds + ' ' + sSecHolder + ' ago';
          } else { 
              var sMinutesHolder = oResult.minutes > 1 ? 'Minutes' : 'Minute';
              oResult.friendlyNiceText = oResult.minutes + ' ' + sMinutesHolder + ' ago';
          }

      } else {
          var sHourHolder = oResult.hours > 1 ? 'Hours' : 'Hour';
          oResult.friendlyNiceText = oResult.hours + ' ' + sHourHolder + ' ago';
      }
  } else { 
      var sDayHolder = oResult.days > 1 ? 'Days' : 'Day';
      oResult.friendlyNiceText = oResult.days + ' ' + sDayHolder + ' ago';
  }

  return oResult;
}
3
Andy B

Quand j'ai essayé la différence entre le même horodatage, cela a donné 0 jours 5 heures 30 minutes 

donc pour l'obtenir exactement j'ai soustrait 5 heures et 30 min

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 + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}
2
Raghukumarachari

J'ai apporté quelques améliorations au compteur de minuterie

//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;
}
1
plutomusang

Vous pouvez utiliser le moment js à cette fin. momentJs 'fromNow ()' vous donnera toute différence de temps par rapport à l'heure actuelle.

var m1 = any date time on moment format;

console.log(m1.fromNow());
0
Abdus Salam Azad

Dans mon cas, je vais stocker le temps en millisecondes sur le stockage de chrome et essayer de trouver diff dans les heures qui suivent.

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
dineshsprabu

J'aime le faire via Epoch.

var now = new Date();
var future = new Date(now.setMinutes(15));

var futureEpoch = moment(future).unix();
var nowEpoch = moment(now).unix();
var differenceInEpoch = nowEpoch - scheduledEpoch ;

console.log("futureEpoch        : " + futureEpoch);
console.log("nowEpoch              : " + nowEpoch);
console.log("differenceInEpoch     : " + differenceInEpoch);

var diffTime = new Date(0); // The 0 there is the key, which sets the date to the Epoch
diffTime.setUTCSeconds(differenceInEpoch);
console.log("new diffTime : " + diffTime);
0

J'utiliserais simplement getTime(); et par exemple Date.now() pour renvoyer la différence en millisecondes:

 //specified date:

var oneDate = new Date("November 02, 2017 06:00:00");

//number of milliseconds since midnight Jan 1 1970 till specified date

var oneDateMiliseconds = oneDate.getTime();

////number of milliseconds since midnight Jan 1 1970 till now

var currentMiliseconds = Date.now(); 

//return time difference in miliseconds

alert(currentMiliseconds-oneDateMiliseconds);
0
Gilbert Cut

Essaye ça :

function SumHours() {
  var smon = document.getElementById('sMon').value ;
  var fmon = document.getElementById('fMon').value ;
  var diff = 0 ;
  if (smon && fmon) {
    smon = ConvertToSeconds(smon);
    fmon = ConvertToSeconds(fmon);
    diff = Math.abs( fmon - smon ) ;
    console.log( 'time difference is : ' + secondsTohhmmss(diff) );
  }

  function ConvertToSeconds(time) {
    var splitTime = time.split(":");
    return splitTime[0] * 3600 + splitTime[1] * 60;
  }

  function secondsTohhmmss(secs) {
    var hours = parseInt(secs / 3600);
    var seconds = parseInt(secs % 3600);
    var minutes = parseInt(seconds / 60) ;
    return hours + "hours : " + minutes + "minutes ";
  }
}
<td>
  <input type="time" class="dataInput" id="sMon" onchange="SumHours();" />
</td>

<td>
  <input type="time" class="dataInputt" id="fMon" onchange="SumHours();"/>
</td>

0
Ehsan