• PHP Help
  • How can I structure the date in this order Month day and year for this script

I have a script that converts a date and a time from a targeted time zone into another time zone. Everything works great, but I find the dateTime() structure to be very annoying by putting the year first and then the month and last the day.

For example:

<?php

$date = new DateTime('2011-6-30 4:52pm', new DateTimeZone('America/Phoenix'));

$date->setTimezone(new DateTimeZone('Asia/Baghdad'));

echo $date->format('n-j-Y g:i A');

?>
I was wondering if there are other methods that I can use to structure the date like this:

<?php

$date = new DateTime('6-30-2011 4:52pm', new DateTimeZone('America/Phoenix'));

$date->setTimezone(new DateTimeZone('Asia/Baghdad'));

echo $date->format('n-j-Y g:i A');

?>
The month first, the day second, and the year last. Do I have to use another method to create a structure like this? Or, if I don't have to change my method, then how can I adjust the code to make it work in that order?

I tried to change it into my desired order but it caused this error:

Fatal error: Uncaught Exception: DateTime::construct(): Failed to parse time string (6-30-2011 4:52pm) at position 0 (6): Unexpected character in C:\xampp\htdocs\xxx.php:3 Stack trace: #0 C:\xampp\htdocs\xxx.php(3): DateTime->construct('6-30-2011 4:52p...', Object(DateTimeZone)) #1 {main} thrown in C:\xampp\htdocs\xxx.php on line 3

    Try it with slashes between the date elements.

    php > $date = new DateTime('6/30/2011 4:52pm', new DateTimeZone('America/Phoenix'));
    php > var_export($date);
    DateTime::__set_state(array(
       'date' => '2011-06-30 16:52:00.000000',
       'timezone_type' => 3,
       'timezone' => 'America/Phoenix',
    ))
    php >
    

    Frankly, I prefer 'yyyy-mm-dd', as that is never ambiguous. (Depending where you are in the world, some people will think 10/12/2019 is October 12th, and some will think it's December 10th.)

      Write a Reply...