function TimezoneDetect(){
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
// Go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
// To ignore daylight saving time look for the lowest offset.
// Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets
var tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off;
假设服务器接收到tzo作为$_POST['tzo'];
$ts = new DateTime('now', new DateTimeZone($_POST['tzo']);
$user_time = $ts->format("F j, Y, g:i a");//will return the users current time in readable format, regardless of whether date_default_timezone() is set or not.
$user_timestamp = strtotime($user_time);
插入/更新date_created=$user_timestamp。
检索date_created时,您可以像这样转换时间戳:
$date_created = // Get from the database
$created = date("F j, Y, g:i a",$date_created); // Return it to the user or whatever
Use Date object to get the long format such as India Standard Time, Eastern Standard Time etc: This is supported by all browsers.
let dateObj = new Date(2021, 11, 25, 09, 30, 00);
//then
dateObj.toString()
//yields
Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time) //I am located in India (IST)
请注意,字符串包含长格式和短格式的时区信息。您现在可以使用regex来获取此信息:
let longZoneRegex = /\((.+)\)/;
dateObj.toString().match(longZoneRegex);
//yields
['(India Standard Time)', 'India Standard Time', index: 34, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]
//Note that output is an array so use output[1] to get the timezone name.
使用Date对象获取短格式,如GMT+0530,GMT-0500等:所有浏览器都支持。
同样,你也可以把短格式拿出来:
let shortZoneRegex = /GMT[+-]\d{1,4}/;
dateObj.toString().match(shortZoneRegex);
//yields
['GMT+0530', index: 25, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]
//Note that output is an array so use output[0] to get the timezone name.