-3

I have a code where I'm using strtotime() to get the date timestamp in PHP.

Have encountered a weird response of it.

Case 1. I got a date like "Tue Jul 2 6pm" : strtotime gives bool(false).

<?php $case1 = strtotime("Tue July 2 6pm"); 
var_dump($case1);
?>

Case 2. If the date is like "Tue Jul 2 6:00pm" :strtotime gives timestamp "1562115600" taking year as current year.

<?php $case2 = strtotime("Tue July 2 6:00pm"); 
var_dump($case2);
?>

Can anyone help me out. Why did strtotime gave bool(false) for the first case ?

What can be done to fix this, Please help ?

Vivek Tankaria
  • 1,301
  • 2
  • 15
  • 35
  • 3
    Use `DateTime::createFromFormat()` and a format that matches the input. `strtotime()` is almost magic, but occasionally it will guess wrong and fail – RiggsFolly Jul 04 '19 at 14:11

2 Answers2

4

check php manual for strtotime:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC),

Returns a timestamp on success, FALSE otherwise.

To fix,it must be converted into a valid format

valid date time formats in php

Community
  • 1
  • 1
-1

To your first point:

<?php
date_create("Tue Jul 2 6pm");
var_dump(date_get_last_errors());

Gives an error: 'The timezone could not be found in the database'. Which means it is not recognized as a valid date/time string. You can explicitly specify the format:

date_create_from_format("D F j ga", "Tue Jul 2 6pm")
geldek
  • 503
  • 2
  • 10
  • 1
    Do you have any explanation about **why** there is such an error message? – Nico Haase Jul 04 '19 at 14:46
  • No. I am not familiar with php internals. For anybody interested here is the source code of the strtotime function https://github.com/php/php-src/blob/php-5.3.23/ext/date/php_date.c#L1397 – geldek Jul 04 '19 at 15:12