date() function returning Invalid Date in Safari and Firefox

前端 未结 5 1373
清酒与你
清酒与你 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-14 04:54

    I ran into this exact same issue today, do not use dashes as a seperator. This works fine in Chrome but not in Safari/iOS, replacing dashes with slashes fixes this issue. The Date function will otherwise break in Safari.

    Incorrect date string with with -

    The following code will return the following

    new Date('03-25-2017');
    

    Chrome:

    Sat Mar 25 2017 00:00:00 GMT+0100 (CET)
    

    Safari:

    Invalid Date
    

    So, simply replace - with /.

    Correct date string with with /

    The following code will return the following

    new Date('03/25/2017');
    

    Chrome:

    Sat Mar 25 2017 00:00:00 GMT+0100 (CET)
    

    Safari:

    Sat Mar 25 2017 00:00:00 GMT+0100 (CET)
    

提交回复
热议问题