skip to Main Content

I’m getting google calendar events, via iCal, which have a date like this:

'20240713T011500Z'

The regular php funcs dont seem to like this format.
This function works, but seems pretty clunky. Is there not a built in way to deal with this format?

function convertGCalDate($gdate){
    $parts = explode('T', $gdate);
    $date  = $parts[0];
    $nums  = str_split($date);
    $date  = $nums[0].$nums[1].$nums[2].$nums[3].'-'.$nums[4].$nums[5].'-'.$nums[6].$nums[7];
    
    $time = trim($parts[1], 'Z');
    $zulu = str_ends_with($parts[1], 'Z');
    
    $nums    = str_split($time);
    $newtime = $nums[0].$nums[1].':'.$nums[2].$nums[3].':'.$nums[4].$nums[5];
    
    $dt = $date.' '.$newtime;
    
    // this is my TZ func, it works, when I finally get the dt into the right format.
    // $datetime = new DateTime($time);
    // $datetime->setTimezone($that_tz);
    // etc
    $dt = getTimeInThisTimezone($dt, $thatTZ = 'Z', $thisTZ = 'America/Los_Angeles', $outformat = null);
    
    return $dt;
    //2024-07-12 7:15 pm

}

$whatIwant =  convertGCalDate('20240713T011500Z');

2

Answers


  1. I assume that input properly validated.
    I think date() and strtotine() should do the trick.

    function convertGCalDate($gdate){
    return echo date('Y-m-d H:i:s',strtotime($gdate));
    }
    
    Login or Signup to reply.
  2. Yeah, you don’t need to do that. You probably also don’t need to do whatever is in the getTimeInThisTimezone() function either.

    var_dump(
        $d = DateTimeImmutable::createFromFormat('YmdTHisO', '20240713T011500Z'),
        $d2 = $d->setTimezone(new DateTimezone('America/Vancouver')),
        $d2->format('Y-m-d g:i a')
    );
    

    Output:

    object(DateTimeImmutable)#1 (3) {
      ["date"]=>
      string(26) "2024-07-13 01:15:00.000000"
      ["timezone_type"]=>
      int(2)
      ["timezone"]=>
      string(1) "Z"
    }
    
    object(DateTimeImmutable)#3 (3) {
      ["date"]=>
      string(26) "2024-07-12 18:15:00.000000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(17) "America/Vancouver"
    }
    
    string(18) "2024-07-12 6:15 pm"
    

    Ref: https://www.php.net/manual/en/datetimeimmutable.createfromformat.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search