0

Here are 3 examples of date and time strings I have

08-01-2019_03-00-34pm
22-01-2019_02-05-06pm
30-01-2019_11-17-07am

I would like to convert these to Unix Time Stamps

For example I have tried this on the first one..

echo (strtotime("08-01-2019"));

This half works, as it gives me a timestamp of 1546905600 which translates back to the correct date, but obviously makes the time 12:00:00am by default. So I'm stuck with how to deal with the time bit

I understand there is a str_replace() function so as long as I know what format I need to make the time bit, I guess I could use that?

ginomay89
  • 249
  • 3
  • 17

1 Answers1

2

Use DateTime::createFromFormat():

$date = DateTime::createFromFormat('d-m-Y_h-i-sa', '08-01-2019_03-00-34pm');

You can then use it to get the timestamp

$date->getTimestamp();  // 1546977634
aynber
  • 22,380
  • 8
  • 50
  • 63
  • This works when I pass `08-01-2019_03-00-34pm` through as a literal string, however I won't be doing this as I'll be pulling in data dynamically from a table in a database. So for example if I pass though `row['file_name']` instead of a literal string it doesn't display anything.. even so when I do a `var_dump()` on `row['file_name']` it tells me it is a string – ginomay89 Feb 01 '19 at 10:41
  • Using `$date = DateTime::createFromFormat('d-m-Y_h-i-sa', $row['file_name']);` should work if it's in that format. If you're not getting a valid date using this, use `var_dump($row['file_name']);` to find out the exact format. – aynber Feb 01 '19 at 13:31