Home > Blockchain >  How would I format a string like Monday-Saturday into an array of the included days?
How would I format a string like Monday-Saturday into an array of the included days?

Time:02-06

I am parsing quite a bit of data that has the format Monday-Thursday or Tuesday-Saturday. How can I format that into an array of the included days without a ton of regex's? Maybe similarly for times such as 11am-8pm

CodePudding user response:

You don't need any regex to do that. You need the build-in date and time classes:

$str = 'Monday-Thursday';

list($begin, $end) = explode('-', $str);

$begin = new DateTime($begin);
$end = new DateTime($end);
$end = $end->modify(' 1 day');

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);

$result = [];

foreach($daterange as $date){
    $result[] = $date->format('l');
}

print_r($result);

demo

Of course, if you want to give your code a little American look, you can use array_map instead of foreach.

$result = array_map(fn($d) => $d->format('l'), iterator_to_array($daterange));

demo

Same thing for hours:

$str = '11am-8pm';

list($begin, $end) = explode('-', $str);

$begin = new DateTime($begin);
$end = new DateTime($end);
$end = $end->modify(' 1 hour');

$interval = new DateInterval('PT1H');
$daterange = new DatePeriod($begin, $interval, $end);

$result = array_map(fn($d) => $d->format('ga'), iterator_to_array($daterange));

print_r($result);

demo

All you have to know are the different date/time formats that are in the PHP manual.

Note that if you want to go from 11pm to 1am, you need to add a day to the $end object.

CodePudding user response:

What about making two from-to variables by exploding the string by "-", then convert the day to number?

  •  Tags:  
  • Related