我在一个看起来像“2013年4月30日”的div中有一个日期,我想将其转换为:30 Tuesday
年利率| 2013年

我已经编写了一些代码来为我进行转换。它在Chrome中可以正常工作,但在Firefox和Firebug控制台中却不能正常工作,它说:Date {Invalid Date}并显示输出,看起来像NaN undefined undefined | NaN。我的代码如下所示或you can also see this Fiddle:

(function ( $ ) {

    $.fn.bcDateModify = function() {
        return this.each(function() {
            var obj = this;
            var srcDate= $(obj).html();
            srcDate = srcDate.replace(/\s+/g, '');

            objDate = new Date(srcDate);
             console.log(objDate);
            var newDate = objDate.getDate();
            var newDay = objDate.getDay();
            var newMonth = objDate.getMonth();
            var newYear = objDate.getFullYear();

            var weekday=new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
            var monthNames=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

            var myhtml ='<div class="date"><span>'+newDate+'</span></div><div class="month-day"><h3>'+weekday[newDay]+'</h3><span>'+monthNames[newMonth]+' | '+newYear+'</span></div>';
            $(obj).html(myhtml);
        });

    };

}( jQuery ));

$(document).ready(function(){
$('.date-obj').bcDateModify();
});

最佳答案

您无法以自己的方式构造日期(至少在Firefox中无法如此),例如,传递字符串“22-Jul-2013”​​。

我改变了这条线

objDate = new Date(srcDate);


var dateSplit = srcDate.split("-");
objDate = new Date(dateSplit[1] + " " + dateSplit[0] + ", " + dateSplit[2]);

以确保正确构造日期。

请参阅更新的小提琴here

关于javascript - 为什么JavaScript的Date对象在Firefox中无效?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17881231/

10-11 14:07