How to deal with different formats of ‘time/date format’

date formattime

Different systems accepts different formats of formating time. E.g.

  • java, jquery: yyyy-MM-dd HH:mm
  • some jquery plugins: yy-mm-dd HH:MM
  • momentjs: YYYY-MM-DD HH:mm
  • ISO-8601: YYYY-MM-DD hh:mm
  • etc

On server I store time as Epoch time. And like to store some timeformat for user, so he see same format everywhere. But I just can't save and pass format string as it will be used differently. I saw various solutions, like restricting choice to 3-5 predefined options, and having list of these options in every system.

How to store time format and show formatted time-date to user in cost-effective way?

—- Example —-

I store time on server as 1412063513 value. In browser user want to see it as 2014-09-30 10:51. So he provide desired timeformat as 'YYYY-MM-DD HH:mm'. I save that format to server, but if i need to use it on server side (java) I got problems, as it is not valid due to capitalized letters. And when other systems trying to query data and format it, same problem arise.

Best Answer

The more formats you support the more problems that will inevitably arise when dealing with datetime formats.

If you intend to validate the inbound value then (I'm sure I'm stating the obvious here but) I wouldn't recommend trying to create your own process to do this, as its often a minefield of problems. DateTime object in PHP is a good at handling a variety of input date formats simply, allowing you to validate and define the output format, therefore allowing you to store the value in a single format, as anom suggests in his comments above. momentjs.com also has similar capabilities. I'm sure lots of others also exist!

If you need to display the date-time again in the original format in which it was received, the only option I can see would be to identify the inbound format in the first place, store this format alongside the original value, and then use the DateTime object format method again using the stored format when building the output content.

Personally I would question carefully if users really need to see the output date in the original format. A standard format would be more consistent and much less of a headache for you in the long term dealing with new formats and bugs etc.

Related Topic