Skip to content

Instantly share code, notes, and snippets.

@bstonedev
Created August 31, 2020 22:52
Show Gist options
  • Save bstonedev/6d5efc42c0a7259f9d941e7bfa246d21 to your computer and use it in GitHub Desktop.
Save bstonedev/6d5efc42c0a7259f9d941e7bfa246d21 to your computer and use it in GitHub Desktop.
PHP date manipulation techniques

PHP date manipulation techniques

php

ISO string date to PHP date object

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

See the PHP date() function for date format references.

Date today in Sydney, Australia

<?php
$today = new DateTime("now", new DateTimeZone('Australia/Sydney'));
var_dump( $today );
?>

Setting the default timezone

<?php
date_default_timezone_set('Asia/Manila');
?>

Converting the timezone

<?php
// The date
date_default_timezone_set('UTC');
$plain_date = date('Y-m-d H:i:s');
/**
 * or... alternatively set it using a string value
$date_in_utc = '2020-01-01 00:00:00';
$date_in_syd = '2020-10-10 00:00:00';
 */

// Prepare the timezones
$utc = new DateTimeZone('+0000');
$syd_utc_offset  = new DateTimeZone('+1000');

// Conversion procedure
$datetime = new DateTime( $date_in_utc, $utc ); // UTC timezone
$datetime->setTimezone( $syd_utc_offset ); // Sydney timezone

// Conversion other way around
$datetime = new DateTime( $date_in_syd, $syd_utc_offset ); // Sydney timezone
$datetime->setTimezone( $utc ); // UTC timezone

echo $datetime->format('Y-m-d H:i:s');
?>

Reference

PHP, date() function, URL: https://www.php.net/manual/en/function.date.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment