Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap-datepicker: How to use specific time zone?

I created a small program to select the date using bootstrap-datepicker and write it to MySQL.

The catch is that this date must be local to Europe/Berlin regardless where the user is at the moment.

$(....).datepicker({ startDate: 'today' });

My question is: how do I set startDate to be local to specific timezone without using server side code (PHP) or any other libraries?

I tried using moment + moment-timezone but it's also showing the local browser date.

var todaysDate = moment().tz('Europe/Berlin').format();
$(...).datepicker({ startDate: todaysDate });

Thanks.

like image 899
Alex G Avatar asked Nov 25 '15 13:11

Alex G


3 Answers

Just needed

moment.tz.setDefault("Europe/Berlin");

After which moment generated the correct date without using tz(). Also make sure that format matches.

var todaysDate = moment().format('D MMM YYYY');
$(...).datepicker({ format: 'dd M yyyy', startDate: todaysDate });
like image 90
Alex G Avatar answered Nov 11 '22 23:11

Alex G


The date object will always be in Local time zone (browser based).

dateObj.getTime() will give you absolute milliseconds.

http://momentjs.com/ is great library for timezone conversions.

EDIT

About how:

 var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
 var losAngeles = newYork.clone().tz("America/Los_Angeles");
 var london     = newYork.clone().tz("Europe/London");
 
 newYork.format();    // 2014-06-01T12:00:00-04:00
 losAngeles.format(); // 2014-06-01T09:00:00-07:00
 london.format();     // 2014-06-01T17:00:00+01:00

and

By default, moment parses and displays in local time.

This is the exact code from their website. If you don't pass America/New_York and just simply moment("2014-06-01 12:00") it will get local time.

moment().utcOffset() function will get you utcOffset if you want to know which timezone moment interprets.

See the demo in jsFiddle

EDIT 2022 momenjs is deprecated, use date-fns or luxon

like image 43
Akshay Avatar answered Nov 11 '22 22:11

Akshay


Maybe something like this can get you in the right direction?

HTML

<div class='input-group date date-time-picker'>
    <input type='text' class="form-control" placeholder="Start Time"/>
    <span class="input-group-addon">
        <i class="glyphicon glyphicon-calendar"></i>
    </span>
</div>

JavaScript

var options = {
    format: 'mm/dd/yyyy hh:ii',
    autoclose: true
};

$('.date-time-picker').datetimepicker(options).on("changeDate", function (e) {
    var TimeZoned = new Date(e.date.setTime(e.date.getTime() + 
                            (e.date.getTimezoneOffset() * 60000)));
    $(this).datetimepicker('setDate', TimeZoned);
});
like image 31
Arg0n Avatar answered Nov 11 '22 23:11

Arg0n