I would like to convert a String date to an Object date.
String date :
jeu. 26 avril 2018 10:25
to this object date
{ ["date"]=> string(26) "2018-04-26 10:34:50.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(12) "Africa/Tunis" }
so far i've tried :
Carbon::createFromFormat("Y-m-d H:i:s", 'jeu. 26 avril 2018 10:25')
i've got an exception :
Unexpected data found. Unexpected data found. The separation symbol could not be found Data missing
u have to change the format:
Carbon::createFromFormat("D. d M Y H:i", 'jeu. 26 avril 2018 10:25')
Note: i assume jeu
is day name.
You need to set locale and proper wildcard characters to read proper date format
You can find placeholder here when working with locale : http://php.net/manual/en/function.strftime.php
this code should work
<?php
// use this only if you working on other locale want to restore OLD locale back
// ====================================
$oldLocale = setlocale(LC_ALL, 0);
var_dump(setlocale(LC_ALL, 'fr_FR'));
// ^ this must return 'fr_FR' then only we confirm locale is set
// if return FALSE then install 'fr_FR' locale for PHP on server
// ====================================
// day name will be having .(dot) at end according abbreviation
// lun., mar., mer., jeu., ven., sam., dim.
$timeChunks = strptime('jeu. 26 avril 2018 10:25', '%a %d %b %Y %H:%M');
// ====================================
// use this only if you working on other locale want to restore OLD locale
setlocale(LC_ALL, $oldLocale);
// ====================================
$date = Carbon::create(
($timeChunks['tm_year'] + 1900) , // year
($timeChunks['tm_mon'] + 1), // month
$timeChunks['tm_mday'], // day
$timeChunks['tm_hour'], // hour
$timeChunks['tm_min'], // min
$timeChunks['tm_sec'] // second
);
// tm_year starts from 1900 so we need to add it
// tm_mon is 0 to 11 so add 1
var_dump($date);
if any doubts then please comment
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.