I have a website that loads data into a MySQL table. Two of the entries in the table are 'startdate' and 'enddate'. 'startdate' is automatic using CURRENT_TIMESTAMP. 'enddate' is chosen by the user using a date picker.
This creates a problem if the user is in a different timezone than the server. For example (I'm in Pacific timezone, server is in Central). If I create an entry at 5pm and choose an end date of 10pm, it goes into the database as 7pm and 10pm, creating a 3-hour window instead of 5. What I want is to convert the end date to Central time (the same as the server). So, using my example, I woul开发者_开发知识库d want the entries in the database to be 7pm and 12 midnight.
I can get the users timezone offset with this javascript:
var d = new Date();
var timezone = -d.getTimezoneOffset()/60;
This returns -7 (I'm in GMT-8, I'm assuming the 1-hour dif is because of daylight savings). My first thought for a solution is to assume the server is in -5, and compare the two (going back to my example, -5 - -7 = 2, so add 2 to the 'enddate').
The problem comes when we switch back to standard time. I assume that my javascript will start to return -8 instead of -7, breaking my function. I know about PHP's date_default_timezone_get(), but that returns a string instead of a number. I guess what I need is a similar function that would (for Central time) return -5 during daylight savings and -6 during standard time.
Use a mysql timestamp field.
Or save all the data in UTC, and then do what needs to be done after in php.
Using MySQL's UTC_TIMESTAMP instead of CURRENT_TIMESTAMP, converts 'startdate' to UTC time. My javascript code:
var d = new Date();
var timezone = -d.getTimezoneOffset()/60;
Can be used to convert 'enddate' to UTC time. Now everything is in UTC and it matches up.
精彩评论