Dates are always hard in web programming. This particular case is something that should be easy, but has odd browser-compatibility issues.

I have a date that came out of a PHP/MySQL application. And I want to display it in a given format.

I was using the date-fns library to do the output formatting, but depending on JavaScript’s ‘Date’ class to parse the input date, which was in MySQL’s Y-m-d H:i:s format.

var dateFormat=require('date-fns/format');

export default {
  methods: {
    'dateToDisplay': function (command) {
      return dateFormat(new Date(command.created_at), 'Do MMM YYYY, HH:mm');
    }
  }
}

This all worked fine in Chrome – the browser I mostly use for development and testing. But when I opened my app in Safari, I got “Invalid date”. What the…?

After a bit of trial, error and research I find that Safari and IE (I only tested IE11) don’t like the Y-m-d format (and browsers are highly inconsistent in parsing dates in general). It seems that this format is not really allowed by the specification of Date() and other browsers (Chrome, Firefox and Edge) all go above-and-beyond the specification in interpreting it correctly.

I tried using date-fns’s parse method to see if that recognised it, but that failed too. It doesn’t look like Moment.js would handle it either.

Anyway, the fix?

Well, you just need to turn it into a format the browsers DO recognise, and this is as simple as turning the hyphens into slashes:

var dateFormat=require('date-fns/format');

export default {
  methods: {
    'dateToDisplay': function (command) {
      // Safari and IE can't parse a MySQL formatted date
      var parsableDate = command.created_at.replace(/-/g, '/');
      return dateFormat(new Date(parsableDate), 'Do MMM YYYY, HH:mm');
    }
  }
}