PHP date format conversion

Here is what I have:

$dateFormat = 'M d, Y';
$dateString = 'January 23, 2010';

I need a timestamp $dateString, so I can do this:

$newFormattedDate = date('Y-m-d', $timestamp);

I tried to use the function strtotime, but it tries to find the format itself and does not always work. In my situation, I know both the date string and the date format.

How to set $timestampto the appropriate value for use with the datefunction?

EDIT: I need this to work on both Linux and Windows.

EDIT: solution must support PHP version 4 or higher

EDIT: MySQL has a function STR_TO_DATEthat takes a date string and a date format and returns a format date string Y-m-d. Any equivalent function for php works for me as well.

+2
4

PHP5.3 API DateTime

$dt = date_create_from_format('M d, Y', 'January 23, 2010');
echo date_timestamp_get($dt);

$dt = DateTime::createFromFormat('M d, Y', 'January 23, 2010');
echo $dt->getTimestamp();

, , DateTime PHP < 5.3, ->getTimestamp() ->format('U'), createFromFormat()

Zend_Date Zend Framework:

$date = new Zend_Date('Feb 31, 2007', 'MM.dd.yyyy');
echo $date->get(Zend_Date::TIMESTAMP);
+7

strptime, mktime strftime:

$ftime = strptime($dateString, $dateFormat);
$timestamp = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1,
                    $ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900);

echo strftime('Y-m-d', $timestamp);

, strptime Windows.

, mktime - strptime ( 0-365, ), , mktime 1 1 . , strptime 1900 , 1900 , mktime.

, , $ftime FALSE, mktime. strptime return FALSE , $dateString $dateFormat.

+3

, PHP, - .

"" ( ) PHP 5.3 .

PHP-land ( PHP 4, ).

- , strtotime .

? / ( ), .

+2
$dateFormat = 'M d, Y'
$timestamp = strtotime($dateString);
echo date($dateFormat, $timestamp); 

, ..

0

Source: https://habr.com/ru/post/1524864/


All Articles