2

How can I convert string "M-d-Y::H:i:s" to unix timestamp in php. I just realized manipulating date and time must be the most time consuming entity in any programming language.

Trivial Question: Why do you think there isn't any universal date time format. Why are there so many variations of same data? AArrhh.

srijan
  • 1,504
  • 1
  • 13
  • 24

2 Answers2

6

The OOP way (requires PHP >= 5.3.0):

$dt = DateTime::createFromFormat("M-d-Y::H:i:s", $input);
$ts = $dt->getTimestamp();

You should of course check the return value of createFromFormat (it's false if an error occurs) but you should also definitely check DateTime::getLastErrors(); otherwise you might be surprised if e.g. your input has a day of "Jan 32". See my answer here for more info.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Fatal error: Call to a member function getTimestamp() on a non-object in C:\my project path. Am I missing anything? $input is actually string in format "M-d-Y::H:i:s" and I am using php 5.4.4 – srijan Jul 18 '12 at 15:21
  • @srijan: You are not checking either the return value (it's obviously `false`) or `getLastErrors()` (it will tell you what's wrong). There's a reason I suggested you do that. – Jon Jul 18 '12 at 15:22
  • Okay I'm getting Undefined Offset Notices in getLastErrors(). My datetime string is literally "12-20-1996::20:00:00". Anything wrong with my format? – srijan Jul 18 '12 at 15:29
  • @Jon please identify the flaw in the question and edit your answer to use the correct format: `m-d-Y::H:i:s` so that future SO readers are not confused. – mickmackusa Mar 23 '17 at 03:49
  • @mickmackusa not sure it's worth it? After all, the readers will have to tweak the format string anyway (that `::` part is not any kind of standard I've seen, and I've seen quite a bit). And in any case the question/answer pair is fine as it stands, is hitting the docs to look at format specifiers if you need to unreasonable? – Jon Mar 24 '17 at 18:11
0

i have this issue service unavailable (with message) ResponseText: Error: Call to a member function getTimestamp() on boolean How to fixed this issue.

mahmoud
  • 1
  • 2