Home > Software engineering >  Convert google TimeOfDay object to string in laravel - php
Convert google TimeOfDay object to string in laravel - php

Time:07-30

I'm working with timePeriod object with gmb library

I receive this response

0 => array:3 [▼
  "weekday" => "SUNDAY"
  "start_time" => {#11764 ▼
     "hours": 10
  }
  "end_time" => {#11740 ▼
     "hours": 21
  }
]

start_time and end_time key can have

{
  "hours": integer,
  "minutes": integer,
  "seconds": integer,
  "nanos": integer
}

I want to format that time to this format:

0 => array:3 [▼
    "weekday" => "SUNDAY"
    "start_time" => "10:00"
    "end_time" => "21:00"
  ]

Sometimes I get an empty array in start_time or close_time because it represent 0 hours (midnight)

0 => array:3 [▼
"weekday" => "SUNDAY"
"start_time" => []
"end_time" => {#13543 ▼
   "hours": 24
}
]

I want to transform that to:

0 => array:3 [▼
"weekday" => "SUNDAY"
"start_time" => "00:00"
"end_time" => "24:00"
]

It is possible by using carbon?

CodePudding user response:

Carbon won't be needed, it's fairly easy to do with pure PHP:

$data = [
  "weekday" => "SUNDAY",
  "end_time" => (object) ["hours" => 10],
  "start_time" => (object) ["hours" => 21],
];
$data['start_time'] = str_pad($data['start_time']->hours ?? 0, 2, '0', STR_PAD_LEFT) . ':' .
    str_pad($data['start_time']->minutes ?? 0, 2, '0', STR_PAD_LEFT);
$data['end_time'] = str_pad($data['end_time']->hours ?? 0, 2, '0', STR_PAD_LEFT) . ':' .
    str_pad($data['end_time']->minutes ?? 0, 2, '0', STR_PAD_LEFT);

Value of $data is now:

[
  "weekday" => "SUNDAY"
  "end_time" => "10:00"
  "start_time" => "21:00"
]

It is for hours:minutes as asked in your post, but it can have also seconds and nanoseconds following the same principle.

  • Related