Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript full text Date() format with PHP carbon

I am generating and sending full date string from javascript Date() function which returns full string date format like this:

Sun Jan 01 2017 00:00:00 GMT+0100 (Central European Standard Time)

Carbon parser wont accept this format for creating the same date on server side. This does not work:

$date = Carbon::parse('Sun Jan 01 2017 00:00:00 GMT+0100 (Central European Standard Time)');

Error Failed to parse time string (Sun Jan 01 2017 00:00:00 GMT+0100 (Central European Standard Time)) at position 41 (l): Double timezone specification

If I remove (Central European Standard Time) works:

$date = Carbon::parse('Sun Jan 01 2017 00:00:00 GMT+0100');

Then it correctly creates date.

Can JS default Date() be used in Carbon somehow or will I have to format date before sending it to Carbon?

like image 471
Primoz Rome Avatar asked Jan 02 '23 15:01

Primoz Rome


1 Answers

Carbon extends PHP's native DateTime class, so you can use createFromFormat instead:

$date = 'Sun Jan 01 2017 00:00:00 GMT+0100 (Central European Standard Time)';
$carbon = Carbon::createFromFormat('D M d Y H:i:s e+', $date);

The important part of the format specification is the + at the end, which tells it to ignore any trailing data.

See https://3v4l.org/Rnen7 for a demo (using DateTime rather than Carbon)

like image 179
iainn Avatar answered Jan 04 '23 04:01

iainn