jQuery Timepicker with unix epoch

The jQuery UI Timepicker is pretty cool. Adds a nice little time selector under the existing jQuery Date Picker calendar.

I needed to read/write timestamps from fields like this:

<input type="text" name="something" class="date_time" value="1477569840">

So I came up with this simple solution:

$('.date_time').each(function(){
    // create a new hidden field for our epoch time storage.
    // copy the name of this field over to the hidden field.
    $thistxt = $(this);
    var currenttime = $thistxt.val();
    $hidden = $('<input/>').attr('type','hidden').attr('name',$thistxt.attr('name')).val( $thistxt.val() );
    $thistxt.attr('name','ignore').after($hidden);
    $thistxt.datetimepicker({
        timeFormat: ucm.settings.time_picker_format,
        timeInput: true,
        controlType: 'select',
        parse: 'loose',
        onSelect: function( datetimeText, datepickerInstance ){
            if(typeof datepickerInstance.hour != 'undefined') {
                var time = datepickerInstance.hour + datepickerInstance.second;
                var date = datepickerInstance['$input'].datepicker("getDate");
                var timestamp = Math.round(new Date(date).getTime()/1000);
                // console.log(timestamp);
                $hidden.val(timestamp);
            }
        }
    });
    if(parseInt(currenttime) > 0) {
        var newtime = new Date(currenttime * 1000);
        $thistxt.datepicker('setTime', newtime);
        $thistxt.datepicker('setDate', newtime);
    }
});

The result is below. I use this in the Ultimate Client Manager.

 

Leave a Reply

Your email address will not be published. Required fields are marked *