How to set 'Now' button on jquery UI datetimepicker to set UTC time?
Asked Answered
S

7

5

I'm using the datetimepicker here. How can I set the now button so that it sets time UTC now instead of the current now per browser?

Stagemanage answered 20/11, 2012 at 18:9 Comment(0)
S
1

This worked for setting the time but not so much for setting the actual date on the calendar.

$.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();
};
Stagemanage answered 20/11, 2012 at 21:8 Comment(0)
B
5

Open your jQuery timepicker addon file and go to the following function

/*
* 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();
};

and simply add the below change,

var now = new Date();
var utcNow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
this._setTime(inst, utcNow);
Bloodyminded answered 24/7, 2013 at 11:50 Comment(0)
S
1

This worked for setting the time but not so much for setting the actual date on the calendar.

$.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();
};
Stagemanage answered 20/11, 2012 at 21:8 Comment(0)
L
1

I had a similar problem, in the end I had to replace the "now" button with a custom one. It is nasty I know but heck otherwise you would probably need to touch the library on each new version.

    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);
    };
Lenssen answered 27/2, 2014 at 18:4 Comment(0)
I
1

My solution is to wrap the original datepicker's _gotoToday function with the _.wrap method from underscore.js and then make the time adjustment.

$.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);
});
Illtreat answered 7/4, 2015 at 10:54 Comment(0)
F
0

Find and replace this code, it's show current local time after click on now button.

/*
 * override "Today" button to also grab the time and set it to input field.
 */
$.datepicker._base_gotoToday = $.datepicker._gotoToday;
$.datepicker._gotoToday = function(id) {
    var inst = this._getInst($(id)[0]);
    this._base_gotoToday(id);
    var tp_inst = this._get(inst, 'timepicker');
    var tzoffset = $.timepicker.timezoneOffsetNumber(tp_inst.timezone);
    var now = new Date();
    var utcNow = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds());
    this._setTime(inst, utcNow);
    tp_inst._onSelectHandler();
};
Fulton answered 17/11, 2015 at 11:18 Comment(0)
S
0

Still a problem for many... although you CAN change the source code to always use UTC time, it is not a solution in many cases, as you might need both UTC functionality AND standard (local time) functionality on the same page.. so.. my solution is this to hide the now button on UTC timepicker types.

NOTE! its not perfect, I know, as the timeout fires after the now button is showed it might give a short "blink".. but its ok for me. It hides the "now button" on in the pickers I need it to, and I dont need to change the datetimepicker script!

    // 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      
    });     
Sulphuryl answered 15/11, 2017 at 7:55 Comment(0)
B
0

You can hijack the date function to set all dates to 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();
      }
   }
};
Bide answered 11/6, 2021 at 1:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.