0

I have this kind of string 09:00-18:00, I want to get 2 \DateTime. The time of the right part returns an object and that of the left part returns another object. I tried to use split, but the my solution does not seems great that's why I'm asking for another solution. This is my solution:

    // Get start time and end time separated by "-"
    $split = \preg_split('/[\s-]+/', $line['intervention_hour']);
    // Get hour number and minute separated by "h"
    $start = \preg_split('/[:]+/', $split[0]);
    $end = \preg_split('/[:]+/', $split[1]);

Any help would be appreciated.

1
  • 1
    What are your expecting result? Can you make it clear. Commented Nov 7, 2019 at 10:25

3 Answers 3

1

If you are sure your that your input will always have the same structure, you could use something like this:

list($start, $end) = explode('-', str_replace(':','h','09:00-18:00'));

Your variable $start will contain '09h00' and $end will contain '18h00'

Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to check if my string flow this format "09:00-18:00" ?
1

You need to use DateTime::createFromFormat

$line = '09:00-18:00';

$split = explode('-', $line);

$start = DateTime::createFromFormat ( 'H:m', $split[0]);
$end = DateTime::createFromFormat ( 'H:m', $split[1]);

print_r($start);
echo '>>>';
print_r($end);

You can check the online Demo

1 Comment

Is it possible to check if my string flow this format "09:00-18:00" ?
1

date_create and new DateTime recognize hh:mm and hh:mm:ss even without format specifications. The date is set to the current date.

$line = '09:00-18:00';

$parts = explode('-', $line);

$start = date_create($parts[0]);
$end   = date_create($parts[1]);

var_dump($start, $end);

Output:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2019-11-07 09:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/Berlin"
}
object(DateTime)#2 (3) {
  ["date"]=>
  string(26) "2019-11-07 18:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/Berlin"
}

A very short variant that returns an array with 2 datetime objects:

$line = '09:00-18:00';

$array = array_map('date_create',explode('-', $line));

Update:

A strict format check can be realized with regular expressions.

if(preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]-([01][0-9]|2[0-3]):[0-5][0-9]$/',$line)){
  //processing

}
else {
  //format error
}

1 Comment

Is it possible to check if my string flow this format "09:00-18:00" ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.