How to set javascript global timezone
本问题已经有最佳答案,请猛点这里访问。
我当前的时区是IST,我希望它是动态的,例如,如果我在数据库中将时区设置为PST,那么我需要将其设置为javascript,每当我尝试创建日期对象时,它应该在PST中返回时间。
如果没有浪费太多时间,我想知道是否有可能是否可能?
无论如何我在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | var currentDate = new Date(new Date().getTime()); // local system date var timezoneOffset = time_zone_offset; //Convert current dateTime into UTC dateTime var utcDate = new Date(currentDate.getTime() + (timezoneOffset * 60000)); //console.log(utcDate); //Convert date string (2015-02-02 07:12:13) in date object var t = date.split(/[- :]/); var today = new Date(); // Apply each element to the Date function var date = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]); //date = new Date(date); var dateDiff = Math.floor((utcDate.getTime()/1000)) - Math.floor((date.getTime()/1000)); var formatedDate = ''; var time = ''; var fullDays = Math.floor(dateDiff/(60*60*24)); var fullHours = Math.floor((dateDiff-(fullDays*60*60*24))/(60*60)); var fullMinutes = Math.floor((dateDiff-(fullDays*60*60*24)-(fullHours*60*60))/60); var fullSeconds = Math.floor((dateDiff-(fullDays*60*60*24)-(fullHours*60*60)-(fullMinutes*60))); var dayArray = new Array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'); var monthArray = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Nov','Dec'); //console.log(dateDiff); date = new Date(date.getTime() - (timezoneOffset * 60000)); if(fullDays > 2){ //var dt = new Date(date*1000); time = monthArray[date.getMonth()]+' '+date.getDate()+' at '+formatAMPM(date); } else if(fullDays == 2){ time = '2 days'; } else if(today.getDate() > t[2]){ time = 'Yesterday at '+formatAMPM(date); } else if(fullHours > 0) { time = fullHours + ' hours'; if(fullHours == 1) { time = fullHours + ' hour'; } } else if(fullMinutes > 0) { time = fullMinutes + ' mins'; if (fullMinutes == 1) { time = fullMinutes + ' min'; } } else { time = 'Just now'; } return time; |
如果我要处理客户端站点时区,我会使用Moment.js和Moment Timezone。 简单的JS日期很痛苦。
它是一个很大的lib,所以如果它只是一次性的事情你想要它最好不要使用它只是从服务器发送时区并用用户的站点时区抵消它