Showing posts with label datetime. Show all posts
Showing posts with label datetime. Show all posts

Monday, September 10, 2018

How do I convert to/from 24-hour time and AM/PM time in PHP?

In databases, times and datetimes may be stored as "13:30:00" or "1984-05-01 15:45:59".

But you may want to convert this to something that displays with AM/PM, or maybe you want to collect a time that is AM/PM and store it according to your DB schema.

You can display 24-hour time in AM/PM with...

print date('G:ia', strtotime("13:30:00"));

And a 24-hour datetime with in AM/PM with...

print date('Y-m-d G:ia', strtotime("1984-05-11 13:30:00"));

If you wanted to go in the opposite direction, and display an AM/PM time with 24-hour time...

print date('H:i:s', strtotime("1:30 AM"));

And if you want to display AM/PM datetime in 24-hour datetime format...

print date('Y-m-d H:i:s', strtotime("1:30 AM"));

Saturday, September 8, 2018

What are the Best Practices for Database DateTime Storage?

Dates are datetimes are common values that coders are going to want to save. But what is the ideal format?

With MySQL, you have the options of Date (default "0000-00-00"), DateTime (default "0000-00-00 00:00:00"), and even Year ("default "0000").

Any of these should fit your purposes for storing recent data. The only limits are that Date and DateTime cannot store years older than 1000, and Year has even smaller range of valid values.

There are advantages to storing dates this way: timezones are built-in to MySQL which can be applied or unapplied easily, the data is fit into as few bits as possible to get you the best storage, you can always sort by using the "greater than" or "lesser than" operators, etc..

Some people store this value as a string. But that is quite a bit more data to hold into the system, and it will accept invalid date/datetime values. This should be avoided.

Some people store this value as an integer, using the epoch time schema. But epoch time is timezone-less, and there will be no way for MySQL to be able to adjust or unadjust this time for timezones. This should be avoided.

Use MySQL's Date or DateTime.