问题
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.
回答1:
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 });
回答2:
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
回答3:
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);
});
来源:https://stackoverflow.com/questions/33918017/bootstrap-datepicker-how-to-use-specific-time-zone