15

I have a form which posts date information month, day, yeah, hour, minute, am/pm. How do i encode/decode this to and from unixtime using php?

mrpatg
  • 10,001
  • 42
  • 110
  • 169
  • If I search SO with your title the first 7 or so hits contain the same answer you selected. – Mike B Nov 04 '09 at 00:31

2 Answers2

38

mktime() - Get Unix timestamp for a date

echo mktime(23, 24, 0, 11, 3, 2009);
1257290640

To handle AM/PM just add 12 to hours if PM.

mktime($isAM ? $hrs : ($hrs + 12), $mins, $secs, $m, $d, $y);

Alternatively you could use strtotime():

strtotime() - Parse about any English textual datetime description into a Unix timestamp

echo strtotime("2009-11-03 11:24:00PM"); 
1257290640
Michał Niedźwiedzki
  • 12,859
  • 7
  • 45
  • 47
  • using strtotime() is +1 for simplicity – risnandar Oct 27 '12 at 11:43
  • 1
    When using strtotime don't forget about `...Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components...` – Eugene van der Merwe Nov 23 '13 at 10:08
  • "To handle AM/PM just add 12 to hours if PM." This is tricky and will produce an error whenever the hour is 12. According to your statement, 10PM = (10 + 12) and that's true, but 12PM = (12 + 12) is wrong. Your statement works for all hours except for 12. In all logic, 12 PM should be 0 AM and 12 AM should be 0 PM. Or.. the difference between 10 apples and 12 apples is 2. The difference between 10 bananas and 12 bananas is 2. The difference between 10PM and 12PM = 14. – Kobbe Jul 14 '17 at 05:41
3

Use the mktime function

Jacob
  • 77,566
  • 24
  • 149
  • 228