new DateTime php code example

Example 1: date now php

date('Y-m-d H:i:s')

Example 2: php datetime

/**
 * Its always best to use a datetime object
 */
$dateTime = new \DateTime();
/**
 * You can get the string by using format
 */
$dateTime->format('Y-m-d H:i:s');

Example 3: php datetime create

$date = DateTime::createFromFormat('d-m-Y', '15-12-2020');

Example 4: datetime php

# From a date Object:
date_format ( DateTimeInterface $object , string $format )

# From the current time
$dateTime = new \DateTime(); 
// or pass a string or int ->`DateTime($date_time)`
$dateTime->format('y-j-d H:i:s T'); #print ex: 21-2-02 16:00:01 PST

# Or a quick one-liner:
date('g:i A m-d-Y', strtotime($date_time)); #print ex: 2:00 PM 02-02-2021

Example 5: datetime php

$dateTime = new \DateTime();
$dateTime->format('Y-m-d H:i:s');

Tags:

Php Example