将字符串转换为日期对象总是最好的方法是手动解析它,除非您有一个非常受控的环境。以下应该做的工作:
// Use date string to create a UTC time to pass to Date constructor
// Expected format is day mon year hh:mm:ss GMToffset (timezone name)
// e.g. Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)
function parseDate(s) {
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
var s = s.split(/[ :]/g);
var offset = s[7];
// Deal with offset
var sign = offset.indexOf('-') >= 0? -1 : 1;
var len = offset.length;
var offMins = sign * offset.substring(len-4, len-2) * 60 + sign * offset.substring(len-2, len);
var mins = s[4] - offMins;
return new Date(Date.UTC(s[3], months[s[1].toLowerCase()], s[2], s[4], mins, s[6]));
}
var s = 'Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)';
alert(parseDate(s)); //Fri 27 Jun 2008 17:00:00 GMT+1000
然后,您可以根据需要格式化日期:
function formatDateUS(d) {
function z(n){return (n<10? '0':'') + n}
return z(d.getMonth()+1) + '/' + z(d.getDate()) + '/' + d.getFullYear();
}
formatDateUS(parseDate(s)); // 06/27/2008