Reputation: 35
I am reading the data from an excel sheet and inserting into MySQL table. In this process, I am converting the timestamp (string) to datetime using the PHP method strtotime()
.
$timestamp = date('Y-m-d H:i:sa',strtotime(trim($value->Time)));
This is failing in some cases.
Example:
echo date('Y-m-d H:i:s',strtotime('04-13-2018 0:00:53'));
echo date('Y-m-d H:i:s',strtotime('04-12-2018 0:00:53'));
Output:
1970-01-01 00:00:00
2018-12-04 00:00:53
Can anyone help me how can I solve this issue?
Sample Strings for which it is failing:
04-12-2018 0:00:53
04-12-2018 0:01:53
04-12-2018 0:02:53
04-12-2018 0:03:53
04-12-2018 0:04:53
04-12-2018 0:05:53
04-12-2018 0:06:53
04-12-2018 0:07:53
04-12-2018 0:08:54
04-12-2018 0:09:54
04-12-2018 0:10:53
04-12-2018 0:11:53
04-12-2018 0:12:53
04-12-2018 0:13:53
04-12-2018 0:14:53
04-12-2018 0:15:53
04-12-2018 0:16:53
04-12-2018 0:17:53
04-12-2018 0:18:53
04-12-2018 0:19:54
04-12-2018 0:20:54
04-12-2018 0:21:54
04-12-2018 0:22:53
04-12-2018 0:23:54
04-12-2018 0:24:53
04-12-2018 0:25:54
Upvotes: 2
Views: 12570
Reputation: 49218
The string format is wrong for strtotime()
and the (I don't recall the technical term) "American-formatted" value:
echo date('Y-m-d H:i:s', strtotime('04-13-2018 0:00:53'));
echo date('Y-m-d H:i:s', strtotime('04/13/2018 0:00:53'));
GIves:
1970-01-01 01:00:00
2018-04-13 00:00:53
Essentially, you gave strtotime()
the (what's it called?) "European date time" value. It's the -
that denotes the day is the first part, not month.
This bit me a long time ago.
Upvotes: 2
Reputation: 23958
To add to what has already been answered.
The reason you get 1970 is beacause strtotime returns false if it can't parse the date.
And 0 (false) unix time is 1970.
Upvotes: 1
Reputation: 19764
Your format is not a format that the parser understands.
In your case 13
is not a "month". So the parser doesn't understand to date.
You should use DateTime::createFromFormat()
:
$date = DateTime::createFromFormat('m-d-Y H:i:s','04-13-2018 0:00:53');
echo $date->format('Y-m-d H:i:s');
Output:
2018-04-13 00:00:53
Note that the format could also be: 'm-d-Y G:i:s'
with G
for "24-hour format of an hour without leading zeros".
Upvotes: 8