2014-05-01 20 views
7

Ho due campi di input per inserire la data, che è un datepicker jQuery. Usando che posso selezionare le date. Sono le date di check in e check out.Calcolare la differenza tra la data e l'ora immesse?

Analogamente ho due caselle di selezione, da cui posso selezionare l'ora. Sono il check in e il check out.

Esempio:

Check in date: 01/05/2014 
Check in time: 13:00 


Check out date: 04/05/2014 
Check out time: 18:00 

voglio il risultato: Differenza tra (2014/01/05 13:00) e (2014/04/05 18:00) come 3 giorni 5 ore

Fiddle

In questo momento sto ottenendo il risultato NAN

seguito è lo script che sto usando:

$(document).ready(function(){ 
    $("#diff").focus(function(){ 
     var start = new Date($('#din').val()); 
     var end = new Date($('#dou').val()); 
     var diff = new Date(end - start); 
     var days = Math.floor(diff/1000/60/60/24); 
     var hours = Math.floor((diff % (1000 * 60 * 60 * 24))/1000/60/60); 
     $("#diff").val(days+' Day(s) '+hours+' Hour(s)'); 
    }); 
}); 
+0

prega, pubblicare qui il codice – hindmost

+0

@hindmost ho creato un violino compresi tutti il ​​mio codice: http: // jsfiddle.net/u97Ja/2/ –

+1

Ho già notato questo link nel tuo codice. Comunque mi piacerebbe vedere il tuo codice qui – hindmost

risposta

1

Fiddle Demo

$(document).ready(function() { 
    function ConvertDateFormat(d, t) { 
     var dt = d.val().split('/'); //split date 
     return dt[1] + '/' + dt[0] + '/' + dt[2] + ' ' + t.val(); //convert date to mm/dd/yy hh:mm format for date creation. 
    } 
    $("#diff").focus(function() { 
     var start = new Date(ConvertDateFormat($('#din'), $('#tin'))); 
     var end = new Date(ConvertDateFormat($('#dout'), $('#tout'))); 
     console.log(start, end); 
     var diff = new Date(end - start); 
     var days = Math.floor(diff/1000/60/60/24); 
     var hours = Math.floor((diff % (1000 * 60 * 60 * 24))/1000/60/60); 
     $("#diff").val(days + ' Day(s) ' + hours + ' Hour(s)'); 
    }); 
}); 


ConvertDateFormat(d,t) converte la data al formato attuale.

per ottenere new Date('mm/dd/yy hh:mm')


Date
Aggiornamento

Problema

Typo

var end = new Date($('#dout').val()); 
//      ^missing t in id it's dout not dou 

che rende invalido date in modo da ottenere NaN quando si sottrae invalid Date.

Updated Fiddle Demo With your code

+1

Potrebbe aiutare il richiedente (e i futuri lettori) di più se si include una spiegazione di cosa hai fatto e perché risolve il problema, invece di scaricare semplicemente il codice :) – Michelle

+0

@Michelle ci sono. basta modificare il post attendere. –

+0

In mezzo ho trovato il mio errore. Ma il formato della data mi preoccupava. Ma l'hai risolto :-) –

0

utilizzare jQuery DatePicker di scegliere le date

e per la differenza provare questo ..

html

<input type="text" id="date1"> 
<input type="text" id="date2"> 
<input type="text" id="calculated"> 


$(document).ready(function() { 

var select=function(dateStr) { 
     var d1 = $('#date1').datepicker('getDate'); 
     var d2 = $('#date2').datepicker('getDate'); 
     var diff = 0; 
     if (d1 && d2) { 
      diff = Math.floor((d2.getTime() - d1.getTime())/86400000); // ms per day 
     } 
     $('#calculated').val(diff); 
} 

$("#date1").datepicker({ 
    minDate: new Date(2012, 7 - 1, 8), 
    maxDate: new Date(2012, 7 - 1, 28), 
    onSelect: select 
}); 
$('#date2').datepicker({onSelect: select}); 
}); 
1

È possibile utilizzare il DatePicker nativo getDate funzione per ottenere la data oggetto. Quindi, utilizzando le informazioni da this SO answer per quanto riguarda lo tenendo conto dell'ora legale nell'account, è possibile utilizzare le ore della data UTC per ottenere le differenze esatte.

Oltre a rendere l'impostazione della data e ora estremamente semplice, se è possibile modificare il value le opzioni, li impostare i valori effettivi ore, simile a questo:

<select id="tin" name="tin"> 
    <option value="13">13:00</option> 
    <option value="19">19:00</option> 
</select> 

e questo

<select id="tout" name="tout"> 
    <option value="12">12:00</option> 
    <option value="18">18:00</option> 
</select> 

Ciò renderà il codice così facile utilizzando solo le funzioni degli oggetti di data nativi per calcolare le date e le ore, eccetto quando dividiamo per 24 per ottenere i giorni dalle ore, in questo modo:

var _MS_PER_HOUR = 1000 * 60 * 60; // 3600000ms per hour 
var outputTextWithSign = '{0}{1} Days(s) {2}{3} Hours(s)'; // included sign 
var outputTextWithoutSign = '{0} Days(s) {1} Hours(s)'; // no sign 

$(function() { 
    $("#din, #dout").datepicker({ 
     minDate: 0, 
     dateFormat: 'dd/mm/yy' 
    }); 
}); 

$(document).ready(function() { 
    $("#diff").focus(function() { 
     var startDate = $('#din').datepicker('getDate'); 
     var endDate = $('#dout').datepicker('getDate'); 

     // use native set hour to set the hours, assuming val is exact hours 
     // otherwise derive exact hour from your values 
     startDate.setHours($('#tin').val()); 
     endDate.setHours($('#tout').val()); 

     // convert date and time to UTC to take daylight savings into account 
     var utc1 = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), startDate.getHours(), startDate.getMinutes(), startDate.getSeconds()); 
     var utc2 = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(), endDate.getHours(), endDate.getMinutes(), endDate.getSeconds()); 

     // get utc difference by always deducting less from more 
     // that way you always get accurate difference even if in reverse! 
     var utcDiff = utc1 > utc2 ? utc1 - utc2 : utc2 - utc1; 

     // get total difference in hours 
     var msDiff = Math.floor(utcDiff/_MS_PER_HOUR); 

     // get days from total hours 
     var dayDiff = Math.floor(msDiff/24); 

     // get left over hours after deducting full days 
     var hourDiff = Math.floor((msDiff - (24 * dayDiff))); 

     // 
     // write out results 
     // 

     // if you really need to show - sign and not just the difference... 
     var sign = utc1 > utc2 ? '-' : ''; 

     // format output text - with (-)sign if required 
     var txtWithSign = outputTextWithSign.format(dayDiff ? sign : '', dayDiff, hourDiff ? sign : '', hourDiff); 

     // simple format without sign 
     var txtNoSign = outputTextWithoutSign.format(dayDiff, hourDiff); 

     // assign result - switch with/without sign result as needed 
     $("#diff").val(txtWithSign); 
     //$("#diff").val(txtNoSign); 
    }); 
}); 

// Helper for easy string formatting. 
String.prototype.format = function() { 
    //var s = arguments[0]; 
    var s = this; 

    for (var i = 0; i < arguments.length; i++) { 
     var reg = new RegExp("\\{" + i + "\\}", "gm"); 
     s = s.replace(reg, arguments[i]); 
    } 

    return s; 
} 

DEMO - Get Day e la differenza ore, prendendo legale in considerazione


+0

vorrei votare la risposta invece di risposta accettata (@Tushar Gupta) come ho commentato la sua risposta –

+0

@AshokDamani: ho letto il tuo commento sull'ora -1 e ho dovuto guardare il mio codice. Mi ci è voluto del tempo per capire se per qualche ragione quando si deduce 'utc2 - utc1' quando' utc1' era più grande i risultati sono stati tutti strani. Sono sicuro che c'è un modo migliore ma ho calcolato le differenze alla fine sottraendo sempre più piccolo da aggiunto il '-', se necessario, alla fine.Ho incluso entrambe le opzioni ora sia per l'inclusione di un segno' -' oppure no.Un'aggiunta anche comoda funzione di formattazione.Il codice dovrebbe ora funzionare per tutti gli scenari. – Nope

Problemi correlati