PHP Time/Date Cheatsheet
Side Note
I have a package to help with time/date manipulation which itself makes use of the brick/date-time package. If you need to do some complicated stuff, then I would recommend using these packages.
Converting User Input
You now have the unix timestamp (number of seconds as an integer, since 1st January 1970)
-
to be English, and dates with /
to be American.
Since the timestamp is just an integer, you can print it or perform maths with it.
Converting To Human Form
Use the date() function to output in a human readable form. E.g.
Be careful not to do this:
Form Input Type - Date
If you are using a date input field and pre-populating the value, you need to use code like this:
Working With DateTime
If you need to create a DateTime object, then here are some useful snippets:
Create From Specified Date Format
Create From MySQL Date
The MySQL date format is actually already in Y-m-d
format, so one can just use it directly in the constructor like so:
Convert DateTime To MySQL Format
Working With Brick\DateTime
Create LocalDate From MySQL / PgSQL Date String
The following is a quick way to convert from a MySQL or PgSQL date string to a LocalDate object. This can easily be done because it is already in the format that the DateTime object expects
Misc
Convert Time to Seconds
If you want to know how many seconds a time like 36 minutes past 9 AM is in seconds since midnight execute the following:
This is also the same as:
Getting Current MySQL Timestamp String
If you want to create the timstamp string and insert it rather than rely on MySQL creating the timestamp for you, then you can use this:
Update File Time
The following snippet will programmatically set a file to have been edited at a specific unix timestamp.
References
- Stack Overflow - How to convert a "HH:MM:SS" string to seconds with PHP?
- phptutorial.net - PHP DateTime
First published: 16th August 2018