1

I have an array which contains time values in GMT. :

Array
(
    [0] => Array
        (
            [h] => 5
            [m] => 0
         )
)

Here Array[0][0] is the array for start time and Array[0][1] is the array for end time.

Now what I am creating time using date time as:

    $timezone = new DateTimeZone("Asia/Kolkata"); //Converting GMT to IST.

    $startTime = new DateTime();
    $startTime->setTime($Array[1][0]["hour"], $Array[1][0]["minute"]);
    $startTime->setTimezone($timezone);
    $startTime->format('h:i a');   //output 10:30 PM // Should be 10:30 AM

    $endTime = new DateTime();
    $endTime->setTime($Array[1][1]["hour"], $Array[1][1]["minute"]);
    $endTime->setTimezone($timezone);
    $endTime->format('h:i a');    //output 10:30 PM //ok

So My $startTime and $endTime both has the same value of `10:30` PM but I want the startTime to have value of `10:00 AM`because its period was `AM` in the array.
1
  • 1
    In your code you never access [period] inside the array. So, how is the program supposed to know which it is? Commented Dec 16, 2017 at 13:05

2 Answers 2

1

When creating new Datetime object You have to specify timezone, because default value is taken from PHP configuration and this may not be set to GMT. So initialization of $startTime and $endTime should be:

$startTime = new DateTime('', new DateTimeZone('GMT'));
$endTime = new DateTime('', new DateTimeZone('GMT'));

Then when You are using setTime() You have to add 12 hours when PM period is taken. It should look like that:

$startTime->setTime($Array[1][0]["hour"] + ($Array[1][0]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);
$endTime->setTime($Array[1][1]["hour"] + ($Array[1][1]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);

Rest of the code looks fine, besides in You example $Array[1] is undefined. $Array[0] is set.

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

Comments

1

You could also use DateTime::createFromFormat():

$d = DateTime::createFromFormat('g:m A', '5:30 PM', new DateTimeZone('GMT'));
$d->setTimeZone(new DateTimeZone('Asia/Kolkata'));
var_dump($d->format('Y-m-d H:i:s'));

Gives:

string(19) "2017-03-16 22:30:00"

You can create the string '5:30 PM' by combining the elements of your array. Please note that you must add a leading 0 to the minutes if they are less than 10, e.g: 9 minutes -> 09

Comments

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.