开发者

Convert RFC 822 date to valid Date for javascript

I'm using a script calendar that when I choose a date, it convert it to a new format (yyyy-mm-dd)

It works in most browser but in Firefox and Opera, I get an invalid date format because the format i work with is RFC 822.

I'm looking for a way to convert this date format

example:

Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)

and change it to

2011-09-08

Could that be done in javascript ?

UPDATE

Here's my code trying to replace the (EDT) to nothing

$(".taskDate").datepick({
          onSelect: function(selectedDate){
            selectedDate = selectedDate.replace(/ \(.+\)/,开发者_如何学C '');
            //alert(selectedDate);
            var newDate = new Date(selectedDate);
            $(".selectedDate").text(newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate());
            location.href="index.php?date="+newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate();
          }
        });

Now I get an error

selectedDate.replace is not a function

How come ?

UPDATE 2

Fixed it because it seems that it was an object and not a darn string. Added

selectedDate = selectedDate.toString();

before the new Date();

Now it's working for all browsers...


Works in Firefox6, see my jsfiddle.

var sOriginalDate = 'Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)';
var oDate = new Date(sOriginalDate);
var iMonth = oDate.getMonth() + 1;
var iDay = oDate.getDate();
var sNewDate = oDate.getFullYear() + '-'
    + (iMonth < 10 ? '0' : '') + iMonth + '-'
    + (iDay < 10 ? '0' : '') + iDay;
alert(sNewDate);


Since the date is RFC 822 you could parse it to a valid Date (the ending EDT does not affect the result):

var dateAsDateObject = new Date(Date.parse(dateInRFC822Format));

This will work with dateInRFC822Format equal to either "Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)" or "Thu Sep 08 2011 12:00:00 GMT-0400"

Now you can get the info you require from dateAsDateObject:

  • year: dateAsDateObject.getFullYear()
  • month: dateAsDateObject.getMonth()
  • day: dateAsDateObject.getDay()

Note: for formatting, if you don't mind using jqueryui you could also use the $.datepicker.formatDate() method. E.g. var stringRepresentation = $.datepicker.formatDate('yy-mm-dd', dateAsDateObject);


Try:

var mydate = new Date(originaldate);
mydate = mydate.getYear() + '-' + (mydate.getMonth() + 1) + '-' + mydate.getDate();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜