Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Last active August 16, 2023 08:25
Show Gist options
  • Save abelcallejo/b21eed600be7d5ab73e5988cfa261b17 to your computer and use it in GitHub Desktop.
Save abelcallejo/b21eed600be7d5ab73e5988cfa261b17 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 the Philippines

<?php
$today = new DateTime("now", new DateTimeZone('Asia/Manila'));
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
$plain_date = '2020-01-01 00:00:00';
 */

// Prepare the timezones
$utc = new DateTimeZone('+0000');
$ph  = new DateTimeZone('+0800');

// Conversion procedure
$datetime = new DateTime( $plain_date, $utc ); // UTC timezone
$datetime->setTimezone( $ph ); // Philippines timezone

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

Numeric month to String month

$month = 3;
(\DateTime::createFromFormat('!m', $month))->format('F'); \\ March

Reference

PHP, DateTime class, URL: https://www.php.net/manual/en/datetime.format.php

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