您可以使用日期選擇本地getDate特性得到日期對象。然後使用this SO answer中有關的信息將日光節約納入帳戶,您可以使用UTC日期時間來獲取確切的差異。
除了使設置日期時間非常簡單,如果你可以改變你的選擇的value
,它們設置爲實際的小時值,與此類似:
<select id="tin" name="tin">
<option value="13">13:00</option>
<option value="19">19:00</option>
</select>
這
<select id="tout" name="tout">
<option value="12">12:00</option>
<option value="18">18:00</option>
</select>
將使用唯一的本地日期的對象特徵來計算您的日期和時間,由24 dividng時除外擺脫小時的日子使代碼很容易,與此類似:
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 - 獲取日和小時的時差,服用夏令考慮
請,發佈您的代碼在這裏@hindmost我已經建立,包括我的所有代碼小提琴 – hindmost
:HTTP:// jsfiddle.net/u97Ja/2/ –
我已經注意到你的代碼中的鏈接。不過,我想在這裏看到你的代碼 – hindmost