1.将程序内部时区设置为UTC时间.(UTC 也可以叫 GMT)
PHP设置:
date_default_timezone_set("UTC");
Yii设置:
config/main.php 中添加 :'timeZone'=>'UTC',
如此设置后,PHP生成的时间基本都是UTC时间了.例如:
//输出当前UTC时间
date("Y-m-d H:i:s");
2.数据库中存储UTC时间.
可以用PHP控制,也可以通过设置数据库时区来实现.
3.服务端发送到前端的时间均为UTC时间格式, 由JS将其转换为本地时间后进行显示.JS内部数据与显示数据分离.
JS转换函数参考:
1 /** 2 * 将UTC时间转为本地时间 3 * @param string utcTime utc时间字符串 格式 :'Y-m-d H:i:s' 4 * @return string 本地时间字符串 格式 :'Y-m-d H:i:s' 5 */ 6 function utcToLocal(utcTime) { 7 if(utcTime==='0000-00-00 00:00:00' || utcTime===null || utcTime==='' || utcTime===undefined) 8 return utcTime; 9 var locTime = new Date(); //local时间对象 10 utcTime=utcTime.replace("-", "/").replace("-", "/"); //火狐不兼容'-'分隔日期 11 //解析字符串及本地时间赋值 12 locTime.setTime(Date.parse(utcTime)-locTime.getTimezoneOffset()*60000); 13 //本地时间字符串格式化 14 var year = locTime.getFullYear(); 15 var month = preZero(locTime.getMonth()+1); 16 var date = preZero(locTime.getDate()); 17 var hour = preZero(locTime.getHours()); 18 var minute = preZero(locTime.getMinutes()); 19 var second = preZero(locTime.getSeconds()); 20 return year+'-'+month+'-'+date+' '+hour+':'+minute+':'+second; 21 } 22 23 /** 24 * 将本地时间转为UTC时间 25 * @param string locTime utc时间字符串 格式 :'Y-m-d H:i:s' 26 * @return string 本地时间字符串 格式 :'Y-m-d H:i:s' 27 */ 28 function localToUtc(locTime) { 29 if(locTime==='0000-00-00 00:00:00' || locTime==='0000-00-00' || locTime===null || locTime==='' || locTime===undefined) 30 return locTime; 31 var tmpTime = new Date(); 32 var utcTime = new Date(); 33 locTime=locTime.replace("-", "/").replace("-", "/"); //火狐不兼容'-'分隔日期 34 //解析字符串 35 tmpTime.setTime(Date.parse(locTime)); 36 if(locTime.length>10) { 37 var year = tmpTime.getUTCFullYear(); 38 var month = preZero(tmpTime.getUTCMonth()+1); 39 var date = preZero(tmpTime.getUTCDate()); 40 var hour = preZero(tmpTime.getUTCHours()); 41 var minute = preZero(tmpTime.getUTCMinutes()); 42 var second = preZero(tmpTime.getUTCSeconds()); 43 return year+'-'+month+'-'+date +' '+hour+':'+minute+':'+second; 44 } else { 45 //设置日期,保留本地时间(供UTC转换用) 46 utcTime.setFullYear(tmpTime.getFullYear()); 47 utcTime.setMonth(tmpTime.getMonth());utcTime.setMonth(tmpTime.getMonth());//?若不重复,则赋值无效 48 utcTime.setDate(tmpTime.getDate()); 49 var year = utcTime.getUTCFullYear(); 50 var month = preZero(utcTime.getUTCMonth()+1); 51 var date = preZero(utcTime.getUTCDate()); 52 return year+'-'+month+'-'+date; 53 } 54 } 55 //单个数字添加前导0 56 function preZero(str) { 57 return str.toString().length<2 ? '0'+str : str; 58 }