开发者

javascript timezone format

I need to format a javascript Date to send via json to the server. The server expects the time to be in the format according to this example

2开发者_StackOverflow社区011-08-31T06:49:28.931 -0700

which it conveniently tells me when I try to submit something like

2011-08-31T06:49:28.931 -07:00

The trouble I am having is with the timezone part, -0700. I've been looking at the Date API, and don't see a way to specify the timezone format. I can do d.getTimezoneOffset, but it returns 240 (Im in EDT I think) for me.

So, I can convert 240 to 0400 to represent 4 hours. I am worried however about correctness for other timezones. My questions are

1) How to convert the result of the getTimezoneOffset() into the required format, and how to determine what the sign should be (thats the part I am worried about)?

2) Is there a way to get the format off the date object itself so I don't have to do anything custom? If i do d.toString() I get "Wed Aug 31 2011 09:48:27 GMT-0400 (EDT)", so here the timezone part is in the format I want. So it might be possible. Maybe the best solution is to just use a regex to grab the timezone off d.toString()...

3) Extra credit: is the format the server requires some sort of standard?

Update: using match(/^.*GMT(-?\d*)/) returns "-0400" at index 1 of the array. Perhaps I should just use that? Im wondering if that regex will work for all timezones in the context of the sign.


Try this code:

var d=new Date(Date.now()); // sets your date to variable d

function repeat(str,count) { // EXTENSION
  return new Array(count+1).join(str);
};

function padLeft(str,length,char) { // EXTENSION
  return length<=str.length ? str.substr(0,length) : repeat(String(char||" ").substr(0,1),length-str.length)+str;
};

var str=padLeft(String(d.getFullYear()),4,"0")+"-"+
        padLeft(String(d.getMonth()),2,"0")+"-"+
        padLeft(String(d.getDate()),2,"0")+"T"+
        padLeft(String(d.getHours()),2,"0")+":"+
        padLeft(String(d.getMinutes()),2,"0")+":"+
        padLeft(String(d.getSeconds()),2,"0")+"."+
        d.getMilliseconds();
//str+=" GMT";
var o=d.getTimezoneOffset(),s=o<0?"+":"-",h,m;
h=Math.floor(Math.abs(o)/60);
m=Math.abs(o)-h*60;

str+=" "+s+padLeft(String(h),2,"0")+padLeft(String(m),2,"0");

alert(str);


You might want to use one of the date/time formatting libraries that bakes in support for this timezone format (such as http://jacwright.com/projects/javascript/date_format/). In any case, you're right: there really is no good way to control the format output.

As far as the regex goes I don't know that all browsers consistently use the GMT string format, so that may not be the best path forward.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜