Date and time

Updated: 23 February 2024

Create a new object

$date = new DateTime('2000-01-01 20:15:05');

/*var_dump($date);
object(DateTime)#649 (3) {
  ["date"]=>
  string(26) "2000-01-01 20:15:05.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}*/

Parse textual datetime description into a Unix timestamp

strtotime(string $dateTimeString, ?int $baseTimestamp = null): int|false

Convert date string to another format

$time = strtotime('11/17/2005');
// var_dump($time);
// int(1132185600)

$newformat = date('d F Y', $time);
// var_dump($newformat);
// string(16) "17 November 2005"

Format a DateTime object as a string

$datetime = new DateTime();
$formatted = $datetime->format('Y-m-d H:i:s');
// var_dump($formatted);
// string(19) "2024-02-23 16:16:24"

Sort multi-dimensional array by value of a DateTime element

$mydates = [
    ['datetime' => new \DateTime('2000-01-03')],
    ['datetime' => new \DateTime('2000-01-01 12:15')],
    ['datetime' => new \DateTime('2000-01-01 12:15:30')]
];
        
usort($mydates, function ($a, $b) {
    return $a['datetime'] < $b['datetime'];
});

/*print_r($mydates);
Array
(
    [0] => Array
        (
            [datetime] => DateTime Object
                (
                    [date] => 2000-01-03 00:00:00.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

        )

    [1] => Array
        (
            [datetime] => DateTime Object
                (
                    [date] => 2000-01-01 12:15:30.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

        )

    [2] => Array
        (
            [datetime] => DateTime Object
                (
                    [date] => 2000-01-01 12:15:00.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

        )
)*/

Leave a comment