如何在jquery UI datetimepicker上设置“Now”按钮来设置UTC时间?

时间:2012-11-20 18:09:25

标签: jquery datepicker jquery-ui-datepicker datetimepicker timepicker

我正在使用datetimepicker here。如何设置now按钮以便现在设置UTC时间而不是现在每个浏览器的当前时间?

7 个答案:

答案 0 :(得分:4)

打开jQuery timepicker addon文件并转到以下函数

/*
* override "Today" button to also grab the time.
*/
$.datepicker._base_gotoToday = $.datepicker._gotoToday;
$.datepicker._gotoToday = function (id) {
    var inst = this._getInst($(id)[0]),
        $dp = inst.dpDiv;
    this._base_gotoToday(id);
    var tp_inst = this._get(inst, 'timepicker');
    selectLocalTimezone(tp_inst);
    var now = new Date();
    this._setTime(inst, now);
    $('.ui-datepicker-today', $dp).click();
};

并简单地添加以下更改

var now = new Date();
var utcNow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
this._setTime(inst, utcNow);

答案 1 :(得分:1)

这适用于设置时间,但不是用于在日历上设置实际日期。

$.datepicker._gotoToday = function (id) {
    var inst = this._getInst($(id)[0]),
    $dp = inst.dpDiv;
    this._base_gotoToday(id);
    var tp_inst = this._get(inst, 'timepicker');
    var now = new Date();
    var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    this._setTime(inst, now_utc);
    $('.ui-datepicker-today', $dp).click();
};

答案 2 :(得分:1)

我遇到了类似的问题,最后我不得不用自定义按钮替换“now”按钮。我知道这很讨厌,但不管怎样,你可能需要在每个新版本上触摸图书馆                  

    window.date = "<?php echo $time; ?>";

    Date.prototype.addHours = function(h) {    
        this.setTime(this.getTime() + (h*60*60*1000)); 
        return this;   
    }
    var previous_time = new Date();
    previous_time.addHours(-1);
    var cur_time = new Date();
    $(".timepicker_from").datetimepicker({
        dateFormat: "mm/dd/yy",
        timeFormat: 'hh:mm:ss',
        showSecond: true,
        hour: previous_time.getUTCHours(),
        minute: previous_time.getUTCMinutes()
    });

    $('.timepicker_from').focus(function(){
        var timezone = jstz.determine();
        $('#timezone').val(timezone.name());
          $( ".ui-datepicker-current" ).replaceWith('<button type="button" style="float: left; margin: .5em .2em .4em; \n\
                                                                               cursor: pointer; padding: .2em .6em .3em .6em;\n\
                                                                               width:auto; overflow:visible;" onclick="set_utc_time_from(date);" > Now </button>' );
    });

    $( ".timepicker_to" ).datetimepicker({
        dateFormat: "mm/dd/yy",
        timeFormat: 'hh:mm:ss',
        showSecond: true,
        hour: cur_time.getUTCHours(),
        minute: cur_time.getUTCMinutes()
    });

    $('.timepicker_to').focus(function(){
        $( ".ui-datepicker-current" ).replaceWith('<button type="button" style="float: left; margin: .5em .2em .4em; \n\
                                                                               cursor: pointer; padding: .2em .6em .3em .6em;\n\
                                                                               width:auto; overflow:visible;" class="" onclick="set_utc_time_to(date);"> Now </button>' );
    });

    function set_utc_time_from(utc){
        var $from = $('input#cdr_from').val(utc);
    };

    function set_utc_time_to(utc){
        var $from = $('input#cdr_to').val(utc);
    };

答案 3 :(得分:1)

我的解决方案是使用_gotoToday中的_.wrap方法包装原始日期选择器的underscore.js函数,然后进行时间调整。

$.datepicker._gotoToday = _.wrap($.datepicker._gotoToday, function (originalHandler) {
    originalHandler.apply(this, _.rest(arguments));
    //utc adjustment:
    var date = new Date();
    date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
    element.datetimepicker('setDate', date);
});

答案 4 :(得分:0)

查找并替换此代码,它会在点击立即按钮后显示当前本地时间。

{{1}}

答案 5 :(得分:0)

许多问题仍然存在问题...尽管您可以将源代码更改为始终使用UTC时间,但在许多情况下它不是解决方案,因为您可能同时需要UTC功能和标准(本地时间)功能page ..所以..我的解决方案是隐藏UTC时间戳类型的现在按钮。

注意!它不完美,我知道,因为在显示现在按钮后超时触发它可能会给出一个短暂的“眨眼”..但它对我来说没问题。它隐藏了我需要它的拾取器中的“现在按钮”,我不需要更改datetimepicker脚本!

    // hides the "now" button (as fast as possible) for the 
    // datetimepickerUTC, as that button only works with local time!
    var datetimepickerUTCNowHider = function( currentDateTime ){
        setTimeout(function () { 
           $('.datetimepickerUTC').datepicker("widget").find(".ui-datepicker-current").hide();
        }, 0.001 );
    };

    //the utc time
    var dateNow = new Date();
    var utc = new Date(dateNow.getTime() + dateNow.getTimezoneOffset() * 60000);

    // the datetimepicker
    $('.datetimepickerUTC').datetimepicker({            
        dateFormat: 'yymmdd', 
        timeFormat: 'HH:mm',
        controlType: 'select',  
        hour: utc.getHours(),
        minute: utc.getMinutes(),
        beforeShow: datetimepickerUTCNowHider,
        onSelect: datetimepickerUTCNowHider,
        showWeek: true      
    });     

答案 6 :(得分:0)

可以劫持日期功能,将所有日期设置为UTC

var daysInMonth     = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var daysInWeek      = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var daysInWeekLong  = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var months          = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var monthsShort     = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var dateReg         = new RegExp("^(\\d{4})(\\d{2})(\\d{2})$");
var dateTimeReg     = new RegExp("^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{0,2})$");
var timeReg         = new RegExp("^(\\d{2})(\\d{2})\\d{0,2}$");

function twoDigit(d) {
   return (d < 10 ? "0" + d : "" + d);
}

Date.prototype.format = function(f) {
   var day         = twoDigit(this.getDate()); 
   var dayWeek     = daysInWeek[this.getDay()]; 
   var dayWeekLong = daysInWeekLong[this.getDay()]; 
   var month       = twoDigit(this.getMonth() + 1); 
   var yearLong    = twoDigit(this.getFullYear()); 
   var yearShort   = twoDigit(this.getFullYear().toString().substring(3,4));
   var year        = (f.indexOf("yyyy") > -1 ? yearLong: yearShort);
   var hour24      = this.getHours(); 
   var hour_am_pm  = twoDigit((hour24 > 12 ? hour24 - 12 : hour24));
   var am_pm       = (hour24 >= 12 ? "PM" : "AM");
   var hour24      = twoDigit(hour24);
   var minute      = twoDigit(this.getMinutes()); 
   var second      = twoDigit(this.getSeconds()); 
   var monthShort  = monthsShort[this.getMonth()]; 
   var monthLong   = months[this.getMonth()]; 

   var dateString  = f.replace(/month/ig, monthLong).replace(/mon/ig, monthShort).replace(/dd/ig, day).replace(/dy/ig, dayWeek).replace(/day/ig, dayWeekLong).replace(/mm/ig, month).replace(/y{2,4}/ig, year).replace(/hh24/ig, hour24).replace(/hh/ig, hour_am_pm).replace(/am_pm/ig, am_pm).replace(/mi/ig, minute).replace(/ss/ig, second);
   return dateString;
} 

var _f = function(item) {
   Date.prototype["get" + item] = Date.prototype["getUTC" + item];
   Date.prototype["set" + item] = Date.prototype["setUTC" + item];
}
var _d = ['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'];
_d.forEach(_f);

Date = class extends Date {
   constructor(...options) {
      if (options.length == 1 && options[0].constructor == Date) {
         if (!isNaN(options[0])) {
            super(options[0]);
         } else {
            super();
         }
      } else if (options.length > 0) {
         if (!isNaN(options[0])) {
            super(Date.UTC(...options));
         } else {
            super();
         }
      } else {
         super();
      }
   }
};