date() function returning Invalid Date in Safari and Firefox

前端 未结 5 1374
清酒与你
清酒与你 2021-02-14 03:57

I am formatting a date in the following way:

date = new Date(\"2013-05-12 20:00:00\");
formattedDate = new Date(date.getFullYear(),date.getMonth(),date.getDate()         


        
5条回答
  •  -上瘾入骨i
    2021-02-14 04:38

    Your date format is not standard for some browsers. To parse custom date time formats you can split it to separate values and use another Date constructor that accepts year, month, day, hours, minutes, seconds and is cross browser compliant. For your case it will be something like this:

    var date = "2013-05-12 20:00:00",
        values = date.split(/[^0-9]/),
        year = parseInt(values[0], 10),
        month = parseInt(values[1], 10) - 1, // Month is zero based, so subtract 1
        day = parseInt(values[2], 10),
        hours = parseInt(values[3], 10),
        minutes = parseInt(values[4], 10),
        seconds = parseInt(values[5], 10),
        formattedDate;
    
    formattedDate = new Date(year, month, day, hours, minutes, seconds);
    

    Working example here http://jsbin.com/ewozew/1/edit

提交回复
热议问题