Home > Mobile >  date-fns.format() is not working in safari browser
date-fns.format() is not working in safari browser

Time:05-05

I am using the date-fns npm package for some date utility. Everything is working fine in the chrome browser. but in mac-safari it's not working. Here is my code snap...

const format = require('date-fns/format');
const parseISO = require('date-fns/parseISO');

const startDateInput = "2020-11-20T09:30:00.000Z";

const formattedStartDate = new Date(format(parseISO(startDateInput), 'MM-dd-yyyy'));
const formattedTodayDate = new Date(format(new Date(), "yyyy-MM-dd"))

console.log('formattedStartDate', formattedStartDate);//IN MAC SAFARI --> Invalid Date 
console.log('formattedTodayDate date1', formattedTodayDate);//IN MAC SAFARI --> Invalid Date 

The same console in chrome is giving Fri Nov 20 2020 18:30:00 GMT 0530 (India Standard Time) a valid date.

Not getting what is the issue with safari browser?

CodePudding user response:

Here is the fix i'm using for the ISO 8601 bug in safari :

parseDate(date) {
    // We parse the date
    const parsed = Date.parse(date);
    // On chrome and firefox it should work
    if (!isNaN(parsed)) {
        return parsed;
    }
    // On safari we need to fix the date before parsing
    return Date.parse(date.replace(/-/g, '/').replace(/[a-z] /gi, ' '));
},

You can adapt that function to your needs for example if you just want the string and not a Date :

fixDateString(date) {
    // We parse the date
    const parsed = Date.parse(date);
    // On chrome and firefox it should work
    if (!isNaN(parsed)) {
        return date;
    }
    // On safari we need to fix the date
    return date.replace(/-/g, '/').replace(/[a-z] /gi, ' ');
},

so in the end 2020-11-20T09:30:00.000Z becomes 2020/11/20 09:30:00.00 on safari

CodePudding user response:

Check your date-fns format string...

  • yyyy - doesn't appear to be supported and should be YYYY (capitalised)
  • MM - 2 digit month ✓
  • dd - 2 character day of the week and should be DD (again, capitalised)

You should probably get further with captialised format strings i.e. YYYY-MM-DD and MM-DD-YYYY.

  • Related