Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JavaScript's Date object is invalid in Firefox?

I have date in a div which looks like "30-Apr-2013" and I want to convert it to: 30 Tuesday APR | 2013

I have write some code to make this conversion for me. Its working fine in Chrome but some how its not working in Firefox and in firebug console it says: Date {Invalid Date} and shows output looks like NaN undefined undefined | NaN. My code looks is below or 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();
});
like image 409
Imran Avatar asked Jul 07 '26 14:07

Imran


1 Answers

You cannot construct a date the way you are (at least in Firefox you can't), for example passing in the string "22-Jul-2013".

I changed this line

objDate = new Date(srcDate);

to

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

to ensure the date was constructed correctly.

See the updated fiddle here.

like image 131
Lewis Avatar answered Jul 09 '26 03:07

Lewis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!