Home > Mobile >  parse int to datetime with carbon
parse int to datetime with carbon

Time:09-28

I have an example value of : 20160530105130 Which I want to convert to a datetime.

I have tried Carbon::createFromFormat('Ym',$value) But that just errors.

I also tried with timestamp, but again error.

Anyone have an idea how I can achive this?

CodePudding user response:

Carbon::createFromFormat('YmdHis', "$value")

CodePudding user response:

Create a DateTime or Carbon object from the string and use the year and month there.

$str = '20160530105130';

$dt = DateTime::createFromFormat('!Ym????????',$str);

var_dump($dt);
//object(DateTime)#2 (3) { ["date"]=> string(26) "2016-05-01 00:00:00.000000" 

Demo: https://3v4l.org/bOJdU

With carbon:

$str = '20160530105130';

$dt = Carbon::createFromFormat('!Ym????????',$str);
echo $dt;  //2016-05-01 00:00:00

Alternatively, the string can also be completely parsed with DateTime. The day and time can then be set to the desired values using the modify method. This variant makes it easier to read what is being done.

$str = '20160530105130';
$dt = date_create($str)->modify('first day of this month 00:00');
//object(DateTime)#2 (3) { ["date"]=> string(26) "2016-05-01 00:00:00.000000"
  • Related