Featured image of post Converting UTC Time to Local Time

Converting UTC Time to Local Time

Convert input time in UTC format to my local time zone

When working with UTC time formats that need conversion to local time (e.g., UTC+8), here’s a breakdown of the process for the input format yyyy-MM-ddTHH:mm:ss.SSSZ:

  • yyyy: 4-digit year
  • MM: 2-digit month (01-12)
  • dd: 2-digit day (01-31)
  • T: Date/time separator
  • HH: 24-hour format hour (00-23)
  • mm: Minutes (00-59)
  • ss: Seconds (00-59)
  • SSS: Milliseconds (3 digits)
  • Z: Timezone offset (e.g., +0100 for UTC+1)

Example Conversion:
Input: 2018-01-01T12:00:00.000+0100 (UTC+1)
Local Output (UTC+8): 2018-01-01 19:00:00.000 (+7 hours)

Implementation using Carbon:

<?php

use Carbon\Carbon;

// Input time with timezone offset
$input = '2018-01-01T12:00:00.000+0100';

// Parse UTC time with offset
$carbon = Carbon::parse($input);

// Convert to China Standard Time (UTC+8)
$carbon->setTimezone('Asia/Shanghai');  // or 'PRC'

// Output with milliseconds (Y-m-d H:i:s.u)
echo $carbon->format('Y-m-d H:i:s.u');  // 2018-01-01 19:00:00.000

Key Notes:

  1. Use Carbon::parse() for ISO 8601 formatted strings
  2. Prefer Asia/Shanghai over PRC for clearer timezone identification
  3. Include .u in format for milliseconds display
  4. Works for any timezone offset in the input (e.g., +0530, -0500)

For non-PHP implementations, similar logic applies using native datetime libraries with timezone support.