Convert one date format into another in PHP










296















Is there a simple way to convert one date format into another date format in PHP?



I have this:



$old_date = date('y-m-d-h-i-s'); // works

$middle = strtotime($old_date); // returns bool(false)

$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00


But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?










share|improve this question
























  • tech-blog.maddyzone.com/php/type-date-convert-php very nice article

    – Rituraj ratan
    Sep 27 '14 at 7:17











  • stackoverflow.com/questions/2167916/…

    – Rasim
    Dec 17 '18 at 18:08















296















Is there a simple way to convert one date format into another date format in PHP?



I have this:



$old_date = date('y-m-d-h-i-s'); // works

$middle = strtotime($old_date); // returns bool(false)

$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00


But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?










share|improve this question
























  • tech-blog.maddyzone.com/php/type-date-convert-php very nice article

    – Rituraj ratan
    Sep 27 '14 at 7:17











  • stackoverflow.com/questions/2167916/…

    – Rasim
    Dec 17 '18 at 18:08













296












296








296


44






Is there a simple way to convert one date format into another date format in PHP?



I have this:



$old_date = date('y-m-d-h-i-s'); // works

$middle = strtotime($old_date); // returns bool(false)

$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00


But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?










share|improve this question
















Is there a simple way to convert one date format into another date format in PHP?



I have this:



$old_date = date('y-m-d-h-i-s'); // works

$middle = strtotime($old_date); // returns bool(false)

$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00


But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?







php date datetime format date-conversion






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 13 '17 at 12:09









Vadim Kotov

4,65663447




4,65663447










asked Jan 30 '10 at 12:58









TomTom

16.6k2479116




16.6k2479116












  • tech-blog.maddyzone.com/php/type-date-convert-php very nice article

    – Rituraj ratan
    Sep 27 '14 at 7:17











  • stackoverflow.com/questions/2167916/…

    – Rasim
    Dec 17 '18 at 18:08

















  • tech-blog.maddyzone.com/php/type-date-convert-php very nice article

    – Rituraj ratan
    Sep 27 '14 at 7:17











  • stackoverflow.com/questions/2167916/…

    – Rasim
    Dec 17 '18 at 18:08
















tech-blog.maddyzone.com/php/type-date-convert-php very nice article

– Rituraj ratan
Sep 27 '14 at 7:17





tech-blog.maddyzone.com/php/type-date-convert-php very nice article

– Rituraj ratan
Sep 27 '14 at 7:17













stackoverflow.com/questions/2167916/…

– Rasim
Dec 17 '18 at 18:08





stackoverflow.com/questions/2167916/…

– Rasim
Dec 17 '18 at 18:08












15 Answers
15






active

oldest

votes


















267














The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.



You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.



PHP 5.3 and up



Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.



PHP 5.2 and lower



You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.



But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:



$old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);





share|improve this answer

























  • Thanks Pekka, just edited my question, tried that but it doesnt seem to work.

    – Tom
    Jan 30 '10 at 13:02











  • I edited the answer while you accepted it :) I added some more examples and references.

    – Pekka 웃
    Jan 30 '10 at 13:07











  • Gotcha, that's indeed the problem. It's a fixed filename I need to convert back into a date (has to be in that format), so I'll figure out a workaround.

    – Tom
    Jan 30 '10 at 13:15











  • Note: According to php.net DateTime exists since PHP 5.2 in PHP core and experimential support for DateTime can be enabled for PHP 5.1 at compilation. secure.php.net/manual/en/datetime.installation.php

    – Charlotte Dunois
    Oct 14 '16 at 16:49



















91














The easiest way to do this is



$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');


You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.



This also avoids the use of strtotime, which can be hard to work with at times.



If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:



$now = new DateTime();
$timestring = $now->format('Y-m-d h:i:s');


This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.






share|improve this answer

























  • And how is it a duplicate if I asked the question before the one you're referring to?

    – Tom
    Jul 11 '12 at 17:01






  • 1





    I've edited the response. I just wanted to point out that these two questions should be linked somehow.

    – ceiroa
    Jul 11 '12 at 18:13











  • available on in php 5.3+

    – Zorox
    Jan 12 '13 at 12:40











  • $timestring = $now->format('Y-m-d h:i:s'); surely? m for months, i for minutes

    – Mark Baker
    Feb 2 '15 at 8:11











  • @madlopt ~ static methods: secure.php.net/manual/en/language.oop5.static.php

    – ceiroa
    Jun 29 '16 at 14:43


















43














The Basics



The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.



$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);


Or as a one-liner:



$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));


Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.



Using DateTime()



As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:



$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');


Working with Unix timestamps



date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:



$new_date_format = date('Y-m-d H:i:s', '1234567890');


DateTime() works with Unix timestamps by adding an @ before the timestamp:



$date = new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');


If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:



  • Trim the last three digits off using substr()

Trimming the last three digits can be acheived several ways, but using substr() is the easiest:



$timestamp = substr('1234567899000', -3);


  • Divide the substr by 1000

You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:



$timestamp = bcdiv('1234567899000', '1000');


To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:



$timestamp = strtotime('1973-04-18');


With DateTime() you can use DateTime::getTimestamp()



$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->getTimestamp();


If you're running PHP 5.2 you can use the U formatting option instead:



$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');


Working with non-standard and ambiguous date formats



Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.



$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
$new_date_format = $date->format('Y-m-d H:i:s');


In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:



$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

$new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');





share|improve this answer
































    26














    Try this:



    $old_date = date('y-m-d-h-i-s');
    $new_date = date('Y-m-d H:i:s', strtotime($old_date));





    share|improve this answer























    • Won't work, strtotime() doesn't recognize the format. Just tried.

      – Pekka 웃
      Jan 30 '10 at 13:16












    • agreed, i just put in the format code from questioner, there should be proper format specified.

      – Sarfraz
      Jan 30 '10 at 14:09











    • It worked for me. My $old_date was something like this 2012-05-22T19:16:37+01:00. Thanks by the way!

      – VishwaKumar
      May 25 '12 at 8:18


















    13














    To convert $date from dd-mm-yyyy hh:mm:ss to a proper MySQL datetime
    I go like this:



    $date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');





    share|improve this answer




















    • 3





      You shouldn't chain these methods unless you are 110% sure $date is a valid date and fits the format. With that being said, an invalid date that doesn't exactly match the format will return: Fatal error: Call to a member function format() on a non-object. Just a heads up!

      – Half Crazed
      Apr 11 '14 at 13:48











    • True, a better solution is to do it in 3 steps with a null check as the middle step.

      – Jelle de Fries
      Apr 18 '14 at 7:41


















    9














    $old_date = date('y-m-d-h-i-s'); // works


    you are doing wrong here, this should be



    $old_date = date('y-m-d h:i:s'); // works


    separator of time is ':'




    I think this will help...



    $old_date = date('y-m-d-h-i-s'); // works

    preg_match_all('/(d+)-(d+)-(d+)-(d+)-(d+)-(d+)/', $old_date, $out, PREG_SET_ORDER);
    $out = $out[0];
    $time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);

    $new_date = date('Y-m-d H:i:s', $time);


    OR




    $old_date = date('y-m-d-h-i-s'); // works

    $out = explode('-', $old_date);
    $time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);

    $new_date = date('Y-m-d H:i:s', $time);





    share|improve this answer

























    • Yes, sure thanks, it's a GUID filename that I want to convert back into a proper date format.

      – Tom
      Jan 30 '10 at 13:11


















    9














    The following is an easy method to convert dates to different formats.



    // Create a new DateTime object
    $date = DateTime::createFromFormat('Y-m-d', '2016-03-25');

    // Output the date in different formats
    echo $date->format('Y-m-d')."n";
    echo $date->format('d-m-Y')."n";
    echo $date->format('m-d-Y')."n";





    share|improve this answer
































      6














      You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.






      share|improve this answer






























        6














        strtotime will work that out. the dates are just not the same and all in us-format.



        <?php
        $e1 = strtotime("2013-07-22T12:00:03Z");
        echo date('y.m.d H:i', $e1);
        echo "2013-07-22T12:00:03Z";

        $e2 = strtotime("2013-07-23T18:18:15Z");
        echo date ('y.m.d H:i', $e2);
        echo "2013-07-23T18:18:15Z";

        $e1 = strtotime("2013-07-21T23:57:04Z");
        echo date ('y.m.d H:i', $e2);
        echo "2013-07-21T23:57:04Z";
        ?>





        share|improve this answer






























          4














          Try this:



          $tempDate = explode('-','03-23-15');
          $date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];





          share|improve this answer
































            4














            This native way will help to convert any inputted format to the desired format.



            $formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
            $dateInput = '01-02-2018'; //date in above format

            $formatOut = 'Y-m-d'; // Your format
            $dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);





            share|improve this answer






























              4














              This solved for me,



              $old = '18-04-2018';
              $new = date('Y-m-d', strtotime($old));
              echo $new;


              Output : 2018-04-18






              share|improve this answer






























                1














                This is the other way you can convert date format



                 <?php
                $pastDate = "Tuesday 11th October, 2016";
                $pastDate = str_replace(",","",$pastDate);

                $date = new DateTime($pastDate);
                $new_date_format = $date->format('Y-m-d');

                echo $new_date_format.' 23:59:59'; ?>





                share|improve this answer






























                  0














                  Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.



                  class dateTranslator {

                  public static function translate($date, $lang)
                  $divider = '';

                  if (empty($date))
                  return null;

                  if (strpos($date, '-') !== false)
                  $divider = '-';
                  else if (strpos($date, '/') !== false)
                  $divider = '/';

                  //spanish format DD/MM/YYYY hh:mm
                  if (strcmp($lang, 'es') == 0)

                  $type = explode($divider, $date)[0];
                  if (strlen($type) == 4)
                  $date = self::reverseDate($date,$divider);

                  if (strcmp($divider, '-') == 0)
                  $date = str_replace("-", "/", $date);

                  //english format YYYY-MM-DD hh:mm
                  else

                  $type = explode($divider, $date)[0];
                  if (strlen($type) == 2)

                  $date = self::reverseDate($date,$divider);

                  if (strcmp($divider, '/') == 0)
                  $date = str_replace("/", "-", $date);



                  return $date;


                  public static function reverseDate($date)
                  $date2 = explode(' ', $date);
                  if (count($date2) == 2)
                  $date = implode("-", array_reverse(preg_split("/D/", $date2[0]))) . ' ' . $date2[1];
                  else
                  $date = implode("-", array_reverse(preg_split("/D/", $date)));


                  return $date;



                  USE



                  dateTranslator::translate($date, 'en')





                  share|improve this answer
































                    0














                    I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.



                    This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.



                    To call it:



                    $TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);


                    Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).



                    Here's the code:



                     <?php 
                    function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)

                    if (!isset($dttm))

                    return "";

                    $timepieces = array();
                    if (is_numeric($dttm))

                    $rettime=$dttm;

                    else

                    $rettime=strtotime($dttm);
                    if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)

                    $rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
                    $timepieces[1]="";

                    else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)

                    preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
                    $rettime=$rettime.".".$timepieces[1];



                    if (isset($dtFormat))

                    // RETURN as ANY date format sent
                    if (strpos($dtFormat,".u")>0) // Deal with milliseconds

                    $rettime=date($dtFormat,$rettime);
                    $rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];

                    else // NO milliseconds wanted

                    $rettime=date($dtFormat,$rettime);


                    else

                    // RETURN Epoch Time (do nothing, we already built Epoch Time)

                    return $rettime;

                    ?>


                    Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).



                     $utctime1="2018-10-30T06:10:11.2185007-07:00";
                    $utctime2="2018-10-30T06:10:11.2185007";
                    $utctime3="2018-10-30T06:10:11.2185007 PDT";
                    $utctime4="2018-10-30T13:10:11.2185007Z";
                    $utctime5="2018-10-30T13:10:11Z";
                    $dttm="10/30/2018 09:10:11 AM EST";

                    echo "<pre>";
                    echo "<b>Epoch Time to a standard format</b><br>";
                    echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
                    echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
                    echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
                    echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
                    echo "</b><br>";
                    echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
                    echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
                    echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
                    echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
                    echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
                    echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
                    echo "<hr>";
                    echo "<hr>";
                    echo "<b>Returned as whatever datetime format one desires</b>";
                    echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
                    echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                    echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                    echo "<p><b>Returned as ISO8601</b>";
                    echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
                    echo "</pre>";


                    Here's the output:



                    Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11

                    Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                    Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                    Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)

                    UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
                    UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
                    UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
                    UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
                    UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
                    NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
                    Returned as whatever datetime format one desires
                    UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
                    UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
                    UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
                    Returned as ISO8601
                    UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601


                    The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.






                    share|improve this answer





















                      protected by Community Feb 3 '14 at 16:31



                      Thank you for your interest in this question.
                      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                      Would you like to answer one of these unanswered questions instead?














                      15 Answers
                      15






                      active

                      oldest

                      votes








                      15 Answers
                      15






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      267














                      The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.



                      You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.



                      PHP 5.3 and up



                      Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.



                      PHP 5.2 and lower



                      You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.



                      But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:



                      $old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
                      $old_date_timestamp = strtotime($old_date);
                      $new_date = date('Y-m-d H:i:s', $old_date_timestamp);





                      share|improve this answer

























                      • Thanks Pekka, just edited my question, tried that but it doesnt seem to work.

                        – Tom
                        Jan 30 '10 at 13:02











                      • I edited the answer while you accepted it :) I added some more examples and references.

                        – Pekka 웃
                        Jan 30 '10 at 13:07











                      • Gotcha, that's indeed the problem. It's a fixed filename I need to convert back into a date (has to be in that format), so I'll figure out a workaround.

                        – Tom
                        Jan 30 '10 at 13:15











                      • Note: According to php.net DateTime exists since PHP 5.2 in PHP core and experimential support for DateTime can be enabled for PHP 5.1 at compilation. secure.php.net/manual/en/datetime.installation.php

                        – Charlotte Dunois
                        Oct 14 '16 at 16:49
















                      267














                      The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.



                      You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.



                      PHP 5.3 and up



                      Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.



                      PHP 5.2 and lower



                      You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.



                      But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:



                      $old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
                      $old_date_timestamp = strtotime($old_date);
                      $new_date = date('Y-m-d H:i:s', $old_date_timestamp);





                      share|improve this answer

























                      • Thanks Pekka, just edited my question, tried that but it doesnt seem to work.

                        – Tom
                        Jan 30 '10 at 13:02











                      • I edited the answer while you accepted it :) I added some more examples and references.

                        – Pekka 웃
                        Jan 30 '10 at 13:07











                      • Gotcha, that's indeed the problem. It's a fixed filename I need to convert back into a date (has to be in that format), so I'll figure out a workaround.

                        – Tom
                        Jan 30 '10 at 13:15











                      • Note: According to php.net DateTime exists since PHP 5.2 in PHP core and experimential support for DateTime can be enabled for PHP 5.1 at compilation. secure.php.net/manual/en/datetime.installation.php

                        – Charlotte Dunois
                        Oct 14 '16 at 16:49














                      267












                      267








                      267







                      The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.



                      You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.



                      PHP 5.3 and up



                      Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.



                      PHP 5.2 and lower



                      You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.



                      But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:



                      $old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
                      $old_date_timestamp = strtotime($old_date);
                      $new_date = date('Y-m-d H:i:s', $old_date_timestamp);





                      share|improve this answer















                      The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.



                      You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.



                      PHP 5.3 and up



                      Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.



                      PHP 5.2 and lower



                      You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.



                      But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:



                      $old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
                      $old_date_timestamp = strtotime($old_date);
                      $new_date = date('Y-m-d H:i:s', $old_date_timestamp);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Oct 6 '10 at 13:11

























                      answered Jan 30 '10 at 13:01









                      Pekka 웃Pekka 웃

                      358k1188431014




                      358k1188431014












                      • Thanks Pekka, just edited my question, tried that but it doesnt seem to work.

                        – Tom
                        Jan 30 '10 at 13:02











                      • I edited the answer while you accepted it :) I added some more examples and references.

                        – Pekka 웃
                        Jan 30 '10 at 13:07











                      • Gotcha, that's indeed the problem. It's a fixed filename I need to convert back into a date (has to be in that format), so I'll figure out a workaround.

                        – Tom
                        Jan 30 '10 at 13:15











                      • Note: According to php.net DateTime exists since PHP 5.2 in PHP core and experimential support for DateTime can be enabled for PHP 5.1 at compilation. secure.php.net/manual/en/datetime.installation.php

                        – Charlotte Dunois
                        Oct 14 '16 at 16:49


















                      • Thanks Pekka, just edited my question, tried that but it doesnt seem to work.

                        – Tom
                        Jan 30 '10 at 13:02











                      • I edited the answer while you accepted it :) I added some more examples and references.

                        – Pekka 웃
                        Jan 30 '10 at 13:07











                      • Gotcha, that's indeed the problem. It's a fixed filename I need to convert back into a date (has to be in that format), so I'll figure out a workaround.

                        – Tom
                        Jan 30 '10 at 13:15











                      • Note: According to php.net DateTime exists since PHP 5.2 in PHP core and experimential support for DateTime can be enabled for PHP 5.1 at compilation. secure.php.net/manual/en/datetime.installation.php

                        – Charlotte Dunois
                        Oct 14 '16 at 16:49

















                      Thanks Pekka, just edited my question, tried that but it doesnt seem to work.

                      – Tom
                      Jan 30 '10 at 13:02





                      Thanks Pekka, just edited my question, tried that but it doesnt seem to work.

                      – Tom
                      Jan 30 '10 at 13:02













                      I edited the answer while you accepted it :) I added some more examples and references.

                      – Pekka 웃
                      Jan 30 '10 at 13:07





                      I edited the answer while you accepted it :) I added some more examples and references.

                      – Pekka 웃
                      Jan 30 '10 at 13:07













                      Gotcha, that's indeed the problem. It's a fixed filename I need to convert back into a date (has to be in that format), so I'll figure out a workaround.

                      – Tom
                      Jan 30 '10 at 13:15





                      Gotcha, that's indeed the problem. It's a fixed filename I need to convert back into a date (has to be in that format), so I'll figure out a workaround.

                      – Tom
                      Jan 30 '10 at 13:15













                      Note: According to php.net DateTime exists since PHP 5.2 in PHP core and experimential support for DateTime can be enabled for PHP 5.1 at compilation. secure.php.net/manual/en/datetime.installation.php

                      – Charlotte Dunois
                      Oct 14 '16 at 16:49






                      Note: According to php.net DateTime exists since PHP 5.2 in PHP core and experimential support for DateTime can be enabled for PHP 5.1 at compilation. secure.php.net/manual/en/datetime.installation.php

                      – Charlotte Dunois
                      Oct 14 '16 at 16:49














                      91














                      The easiest way to do this is



                      $myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
                      $newDateString = $myDateTime->format('m/d/Y');


                      You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.



                      This also avoids the use of strtotime, which can be hard to work with at times.



                      If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:



                      $now = new DateTime();
                      $timestring = $now->format('Y-m-d h:i:s');


                      This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.






                      share|improve this answer

























                      • And how is it a duplicate if I asked the question before the one you're referring to?

                        – Tom
                        Jul 11 '12 at 17:01






                      • 1





                        I've edited the response. I just wanted to point out that these two questions should be linked somehow.

                        – ceiroa
                        Jul 11 '12 at 18:13











                      • available on in php 5.3+

                        – Zorox
                        Jan 12 '13 at 12:40











                      • $timestring = $now->format('Y-m-d h:i:s'); surely? m for months, i for minutes

                        – Mark Baker
                        Feb 2 '15 at 8:11











                      • @madlopt ~ static methods: secure.php.net/manual/en/language.oop5.static.php

                        – ceiroa
                        Jun 29 '16 at 14:43















                      91














                      The easiest way to do this is



                      $myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
                      $newDateString = $myDateTime->format('m/d/Y');


                      You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.



                      This also avoids the use of strtotime, which can be hard to work with at times.



                      If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:



                      $now = new DateTime();
                      $timestring = $now->format('Y-m-d h:i:s');


                      This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.






                      share|improve this answer

























                      • And how is it a duplicate if I asked the question before the one you're referring to?

                        – Tom
                        Jul 11 '12 at 17:01






                      • 1





                        I've edited the response. I just wanted to point out that these two questions should be linked somehow.

                        – ceiroa
                        Jul 11 '12 at 18:13











                      • available on in php 5.3+

                        – Zorox
                        Jan 12 '13 at 12:40











                      • $timestring = $now->format('Y-m-d h:i:s'); surely? m for months, i for minutes

                        – Mark Baker
                        Feb 2 '15 at 8:11











                      • @madlopt ~ static methods: secure.php.net/manual/en/language.oop5.static.php

                        – ceiroa
                        Jun 29 '16 at 14:43













                      91












                      91








                      91







                      The easiest way to do this is



                      $myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
                      $newDateString = $myDateTime->format('m/d/Y');


                      You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.



                      This also avoids the use of strtotime, which can be hard to work with at times.



                      If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:



                      $now = new DateTime();
                      $timestring = $now->format('Y-m-d h:i:s');


                      This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.






                      share|improve this answer















                      The easiest way to do this is



                      $myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
                      $newDateString = $myDateTime->format('m/d/Y');


                      You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.



                      This also avoids the use of strtotime, which can be hard to work with at times.



                      If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:



                      $now = new DateTime();
                      $timestring = $now->format('Y-m-d h:i:s');


                      This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 23 '17 at 12:10









                      Community

                      11




                      11










                      answered Jul 11 '12 at 14:58









                      ceiroaceiroa

                      4,64811618




                      4,64811618












                      • And how is it a duplicate if I asked the question before the one you're referring to?

                        – Tom
                        Jul 11 '12 at 17:01






                      • 1





                        I've edited the response. I just wanted to point out that these two questions should be linked somehow.

                        – ceiroa
                        Jul 11 '12 at 18:13











                      • available on in php 5.3+

                        – Zorox
                        Jan 12 '13 at 12:40











                      • $timestring = $now->format('Y-m-d h:i:s'); surely? m for months, i for minutes

                        – Mark Baker
                        Feb 2 '15 at 8:11











                      • @madlopt ~ static methods: secure.php.net/manual/en/language.oop5.static.php

                        – ceiroa
                        Jun 29 '16 at 14:43

















                      • And how is it a duplicate if I asked the question before the one you're referring to?

                        – Tom
                        Jul 11 '12 at 17:01






                      • 1





                        I've edited the response. I just wanted to point out that these two questions should be linked somehow.

                        – ceiroa
                        Jul 11 '12 at 18:13











                      • available on in php 5.3+

                        – Zorox
                        Jan 12 '13 at 12:40











                      • $timestring = $now->format('Y-m-d h:i:s'); surely? m for months, i for minutes

                        – Mark Baker
                        Feb 2 '15 at 8:11











                      • @madlopt ~ static methods: secure.php.net/manual/en/language.oop5.static.php

                        – ceiroa
                        Jun 29 '16 at 14:43
















                      And how is it a duplicate if I asked the question before the one you're referring to?

                      – Tom
                      Jul 11 '12 at 17:01





                      And how is it a duplicate if I asked the question before the one you're referring to?

                      – Tom
                      Jul 11 '12 at 17:01




                      1




                      1





                      I've edited the response. I just wanted to point out that these two questions should be linked somehow.

                      – ceiroa
                      Jul 11 '12 at 18:13





                      I've edited the response. I just wanted to point out that these two questions should be linked somehow.

                      – ceiroa
                      Jul 11 '12 at 18:13













                      available on in php 5.3+

                      – Zorox
                      Jan 12 '13 at 12:40





                      available on in php 5.3+

                      – Zorox
                      Jan 12 '13 at 12:40













                      $timestring = $now->format('Y-m-d h:i:s'); surely? m for months, i for minutes

                      – Mark Baker
                      Feb 2 '15 at 8:11





                      $timestring = $now->format('Y-m-d h:i:s'); surely? m for months, i for minutes

                      – Mark Baker
                      Feb 2 '15 at 8:11













                      @madlopt ~ static methods: secure.php.net/manual/en/language.oop5.static.php

                      – ceiroa
                      Jun 29 '16 at 14:43





                      @madlopt ~ static methods: secure.php.net/manual/en/language.oop5.static.php

                      – ceiroa
                      Jun 29 '16 at 14:43











                      43














                      The Basics



                      The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.



                      $timestamp = strtotime('2008-07-01T22:35:17.02');
                      $new_date_format = date('Y-m-d H:i:s', $timestamp);


                      Or as a one-liner:



                      $new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));


                      Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.



                      Using DateTime()



                      As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:



                      $date = new DateTime('2008-07-01T22:35:17.02');
                      $new_date_format = $date->format('Y-m-d H:i:s');


                      Working with Unix timestamps



                      date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:



                      $new_date_format = date('Y-m-d H:i:s', '1234567890');


                      DateTime() works with Unix timestamps by adding an @ before the timestamp:



                      $date = new DateTime('@1234567890');
                      $new_date_format = $date->format('Y-m-d H:i:s');


                      If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:



                      • Trim the last three digits off using substr()

                      Trimming the last three digits can be acheived several ways, but using substr() is the easiest:



                      $timestamp = substr('1234567899000', -3);


                      • Divide the substr by 1000

                      You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:



                      $timestamp = bcdiv('1234567899000', '1000');


                      To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:



                      $timestamp = strtotime('1973-04-18');


                      With DateTime() you can use DateTime::getTimestamp()



                      $date = new DateTime('2008-07-01T22:35:17.02');
                      $timestamp = $date->getTimestamp();


                      If you're running PHP 5.2 you can use the U formatting option instead:



                      $date = new DateTime('2008-07-01T22:35:17.02');
                      $timestamp = $date->format('U');


                      Working with non-standard and ambiguous date formats



                      Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.



                      $date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
                      $new_date_format = $date->format('Y-m-d H:i:s');


                      In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:



                      $new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

                      $new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');





                      share|improve this answer





























                        43














                        The Basics



                        The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.



                        $timestamp = strtotime('2008-07-01T22:35:17.02');
                        $new_date_format = date('Y-m-d H:i:s', $timestamp);


                        Or as a one-liner:



                        $new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));


                        Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.



                        Using DateTime()



                        As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:



                        $date = new DateTime('2008-07-01T22:35:17.02');
                        $new_date_format = $date->format('Y-m-d H:i:s');


                        Working with Unix timestamps



                        date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:



                        $new_date_format = date('Y-m-d H:i:s', '1234567890');


                        DateTime() works with Unix timestamps by adding an @ before the timestamp:



                        $date = new DateTime('@1234567890');
                        $new_date_format = $date->format('Y-m-d H:i:s');


                        If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:



                        • Trim the last three digits off using substr()

                        Trimming the last three digits can be acheived several ways, but using substr() is the easiest:



                        $timestamp = substr('1234567899000', -3);


                        • Divide the substr by 1000

                        You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:



                        $timestamp = bcdiv('1234567899000', '1000');


                        To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:



                        $timestamp = strtotime('1973-04-18');


                        With DateTime() you can use DateTime::getTimestamp()



                        $date = new DateTime('2008-07-01T22:35:17.02');
                        $timestamp = $date->getTimestamp();


                        If you're running PHP 5.2 you can use the U formatting option instead:



                        $date = new DateTime('2008-07-01T22:35:17.02');
                        $timestamp = $date->format('U');


                        Working with non-standard and ambiguous date formats



                        Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.



                        $date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
                        $new_date_format = $date->format('Y-m-d H:i:s');


                        In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:



                        $new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

                        $new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');





                        share|improve this answer



























                          43












                          43








                          43







                          The Basics



                          The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.



                          $timestamp = strtotime('2008-07-01T22:35:17.02');
                          $new_date_format = date('Y-m-d H:i:s', $timestamp);


                          Or as a one-liner:



                          $new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));


                          Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.



                          Using DateTime()



                          As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:



                          $date = new DateTime('2008-07-01T22:35:17.02');
                          $new_date_format = $date->format('Y-m-d H:i:s');


                          Working with Unix timestamps



                          date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:



                          $new_date_format = date('Y-m-d H:i:s', '1234567890');


                          DateTime() works with Unix timestamps by adding an @ before the timestamp:



                          $date = new DateTime('@1234567890');
                          $new_date_format = $date->format('Y-m-d H:i:s');


                          If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:



                          • Trim the last three digits off using substr()

                          Trimming the last three digits can be acheived several ways, but using substr() is the easiest:



                          $timestamp = substr('1234567899000', -3);


                          • Divide the substr by 1000

                          You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:



                          $timestamp = bcdiv('1234567899000', '1000');


                          To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:



                          $timestamp = strtotime('1973-04-18');


                          With DateTime() you can use DateTime::getTimestamp()



                          $date = new DateTime('2008-07-01T22:35:17.02');
                          $timestamp = $date->getTimestamp();


                          If you're running PHP 5.2 you can use the U formatting option instead:



                          $date = new DateTime('2008-07-01T22:35:17.02');
                          $timestamp = $date->format('U');


                          Working with non-standard and ambiguous date formats



                          Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.



                          $date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
                          $new_date_format = $date->format('Y-m-d H:i:s');


                          In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:



                          $new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

                          $new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');





                          share|improve this answer















                          The Basics



                          The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.



                          $timestamp = strtotime('2008-07-01T22:35:17.02');
                          $new_date_format = date('Y-m-d H:i:s', $timestamp);


                          Or as a one-liner:



                          $new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));


                          Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.



                          Using DateTime()



                          As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:



                          $date = new DateTime('2008-07-01T22:35:17.02');
                          $new_date_format = $date->format('Y-m-d H:i:s');


                          Working with Unix timestamps



                          date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:



                          $new_date_format = date('Y-m-d H:i:s', '1234567890');


                          DateTime() works with Unix timestamps by adding an @ before the timestamp:



                          $date = new DateTime('@1234567890');
                          $new_date_format = $date->format('Y-m-d H:i:s');


                          If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:



                          • Trim the last three digits off using substr()

                          Trimming the last three digits can be acheived several ways, but using substr() is the easiest:



                          $timestamp = substr('1234567899000', -3);


                          • Divide the substr by 1000

                          You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:



                          $timestamp = bcdiv('1234567899000', '1000');


                          To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:



                          $timestamp = strtotime('1973-04-18');


                          With DateTime() you can use DateTime::getTimestamp()



                          $date = new DateTime('2008-07-01T22:35:17.02');
                          $timestamp = $date->getTimestamp();


                          If you're running PHP 5.2 you can use the U formatting option instead:



                          $date = new DateTime('2008-07-01T22:35:17.02');
                          $timestamp = $date->format('U');


                          Working with non-standard and ambiguous date formats



                          Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.



                          $date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
                          $new_date_format = $date->format('Y-m-d H:i:s');


                          In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:



                          $new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

                          $new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Dec 15 '16 at 16:23

























                          answered Apr 15 '14 at 14:49









                          John CondeJohn Conde

                          186k80372425




                          186k80372425





















                              26














                              Try this:



                              $old_date = date('y-m-d-h-i-s');
                              $new_date = date('Y-m-d H:i:s', strtotime($old_date));





                              share|improve this answer























                              • Won't work, strtotime() doesn't recognize the format. Just tried.

                                – Pekka 웃
                                Jan 30 '10 at 13:16












                              • agreed, i just put in the format code from questioner, there should be proper format specified.

                                – Sarfraz
                                Jan 30 '10 at 14:09











                              • It worked for me. My $old_date was something like this 2012-05-22T19:16:37+01:00. Thanks by the way!

                                – VishwaKumar
                                May 25 '12 at 8:18















                              26














                              Try this:



                              $old_date = date('y-m-d-h-i-s');
                              $new_date = date('Y-m-d H:i:s', strtotime($old_date));





                              share|improve this answer























                              • Won't work, strtotime() doesn't recognize the format. Just tried.

                                – Pekka 웃
                                Jan 30 '10 at 13:16












                              • agreed, i just put in the format code from questioner, there should be proper format specified.

                                – Sarfraz
                                Jan 30 '10 at 14:09











                              • It worked for me. My $old_date was something like this 2012-05-22T19:16:37+01:00. Thanks by the way!

                                – VishwaKumar
                                May 25 '12 at 8:18













                              26












                              26








                              26







                              Try this:



                              $old_date = date('y-m-d-h-i-s');
                              $new_date = date('Y-m-d H:i:s', strtotime($old_date));





                              share|improve this answer













                              Try this:



                              $old_date = date('y-m-d-h-i-s');
                              $new_date = date('Y-m-d H:i:s', strtotime($old_date));






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jan 30 '10 at 13:01









                              SarfrazSarfraz

                              302k65472549




                              302k65472549












                              • Won't work, strtotime() doesn't recognize the format. Just tried.

                                – Pekka 웃
                                Jan 30 '10 at 13:16












                              • agreed, i just put in the format code from questioner, there should be proper format specified.

                                – Sarfraz
                                Jan 30 '10 at 14:09











                              • It worked for me. My $old_date was something like this 2012-05-22T19:16:37+01:00. Thanks by the way!

                                – VishwaKumar
                                May 25 '12 at 8:18

















                              • Won't work, strtotime() doesn't recognize the format. Just tried.

                                – Pekka 웃
                                Jan 30 '10 at 13:16












                              • agreed, i just put in the format code from questioner, there should be proper format specified.

                                – Sarfraz
                                Jan 30 '10 at 14:09











                              • It worked for me. My $old_date was something like this 2012-05-22T19:16:37+01:00. Thanks by the way!

                                – VishwaKumar
                                May 25 '12 at 8:18
















                              Won't work, strtotime() doesn't recognize the format. Just tried.

                              – Pekka 웃
                              Jan 30 '10 at 13:16






                              Won't work, strtotime() doesn't recognize the format. Just tried.

                              – Pekka 웃
                              Jan 30 '10 at 13:16














                              agreed, i just put in the format code from questioner, there should be proper format specified.

                              – Sarfraz
                              Jan 30 '10 at 14:09





                              agreed, i just put in the format code from questioner, there should be proper format specified.

                              – Sarfraz
                              Jan 30 '10 at 14:09













                              It worked for me. My $old_date was something like this 2012-05-22T19:16:37+01:00. Thanks by the way!

                              – VishwaKumar
                              May 25 '12 at 8:18





                              It worked for me. My $old_date was something like this 2012-05-22T19:16:37+01:00. Thanks by the way!

                              – VishwaKumar
                              May 25 '12 at 8:18











                              13














                              To convert $date from dd-mm-yyyy hh:mm:ss to a proper MySQL datetime
                              I go like this:



                              $date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');





                              share|improve this answer




















                              • 3





                                You shouldn't chain these methods unless you are 110% sure $date is a valid date and fits the format. With that being said, an invalid date that doesn't exactly match the format will return: Fatal error: Call to a member function format() on a non-object. Just a heads up!

                                – Half Crazed
                                Apr 11 '14 at 13:48











                              • True, a better solution is to do it in 3 steps with a null check as the middle step.

                                – Jelle de Fries
                                Apr 18 '14 at 7:41















                              13














                              To convert $date from dd-mm-yyyy hh:mm:ss to a proper MySQL datetime
                              I go like this:



                              $date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');





                              share|improve this answer




















                              • 3





                                You shouldn't chain these methods unless you are 110% sure $date is a valid date and fits the format. With that being said, an invalid date that doesn't exactly match the format will return: Fatal error: Call to a member function format() on a non-object. Just a heads up!

                                – Half Crazed
                                Apr 11 '14 at 13:48











                              • True, a better solution is to do it in 3 steps with a null check as the middle step.

                                – Jelle de Fries
                                Apr 18 '14 at 7:41













                              13












                              13








                              13







                              To convert $date from dd-mm-yyyy hh:mm:ss to a proper MySQL datetime
                              I go like this:



                              $date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');





                              share|improve this answer















                              To convert $date from dd-mm-yyyy hh:mm:ss to a proper MySQL datetime
                              I go like this:



                              $date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 18 '17 at 8:48









                              RousseauAlexandre

                              6091014




                              6091014










                              answered Mar 4 '13 at 12:45









                              Jelle de FriesJelle de Fries

                              7901919




                              7901919







                              • 3





                                You shouldn't chain these methods unless you are 110% sure $date is a valid date and fits the format. With that being said, an invalid date that doesn't exactly match the format will return: Fatal error: Call to a member function format() on a non-object. Just a heads up!

                                – Half Crazed
                                Apr 11 '14 at 13:48











                              • True, a better solution is to do it in 3 steps with a null check as the middle step.

                                – Jelle de Fries
                                Apr 18 '14 at 7:41












                              • 3





                                You shouldn't chain these methods unless you are 110% sure $date is a valid date and fits the format. With that being said, an invalid date that doesn't exactly match the format will return: Fatal error: Call to a member function format() on a non-object. Just a heads up!

                                – Half Crazed
                                Apr 11 '14 at 13:48











                              • True, a better solution is to do it in 3 steps with a null check as the middle step.

                                – Jelle de Fries
                                Apr 18 '14 at 7:41







                              3




                              3





                              You shouldn't chain these methods unless you are 110% sure $date is a valid date and fits the format. With that being said, an invalid date that doesn't exactly match the format will return: Fatal error: Call to a member function format() on a non-object. Just a heads up!

                              – Half Crazed
                              Apr 11 '14 at 13:48





                              You shouldn't chain these methods unless you are 110% sure $date is a valid date and fits the format. With that being said, an invalid date that doesn't exactly match the format will return: Fatal error: Call to a member function format() on a non-object. Just a heads up!

                              – Half Crazed
                              Apr 11 '14 at 13:48













                              True, a better solution is to do it in 3 steps with a null check as the middle step.

                              – Jelle de Fries
                              Apr 18 '14 at 7:41





                              True, a better solution is to do it in 3 steps with a null check as the middle step.

                              – Jelle de Fries
                              Apr 18 '14 at 7:41











                              9














                              $old_date = date('y-m-d-h-i-s'); // works


                              you are doing wrong here, this should be



                              $old_date = date('y-m-d h:i:s'); // works


                              separator of time is ':'




                              I think this will help...



                              $old_date = date('y-m-d-h-i-s'); // works

                              preg_match_all('/(d+)-(d+)-(d+)-(d+)-(d+)-(d+)/', $old_date, $out, PREG_SET_ORDER);
                              $out = $out[0];
                              $time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);

                              $new_date = date('Y-m-d H:i:s', $time);


                              OR




                              $old_date = date('y-m-d-h-i-s'); // works

                              $out = explode('-', $old_date);
                              $time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);

                              $new_date = date('Y-m-d H:i:s', $time);





                              share|improve this answer

























                              • Yes, sure thanks, it's a GUID filename that I want to convert back into a proper date format.

                                – Tom
                                Jan 30 '10 at 13:11















                              9














                              $old_date = date('y-m-d-h-i-s'); // works


                              you are doing wrong here, this should be



                              $old_date = date('y-m-d h:i:s'); // works


                              separator of time is ':'




                              I think this will help...



                              $old_date = date('y-m-d-h-i-s'); // works

                              preg_match_all('/(d+)-(d+)-(d+)-(d+)-(d+)-(d+)/', $old_date, $out, PREG_SET_ORDER);
                              $out = $out[0];
                              $time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);

                              $new_date = date('Y-m-d H:i:s', $time);


                              OR




                              $old_date = date('y-m-d-h-i-s'); // works

                              $out = explode('-', $old_date);
                              $time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);

                              $new_date = date('Y-m-d H:i:s', $time);





                              share|improve this answer

























                              • Yes, sure thanks, it's a GUID filename that I want to convert back into a proper date format.

                                – Tom
                                Jan 30 '10 at 13:11













                              9












                              9








                              9







                              $old_date = date('y-m-d-h-i-s'); // works


                              you are doing wrong here, this should be



                              $old_date = date('y-m-d h:i:s'); // works


                              separator of time is ':'




                              I think this will help...



                              $old_date = date('y-m-d-h-i-s'); // works

                              preg_match_all('/(d+)-(d+)-(d+)-(d+)-(d+)-(d+)/', $old_date, $out, PREG_SET_ORDER);
                              $out = $out[0];
                              $time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);

                              $new_date = date('Y-m-d H:i:s', $time);


                              OR




                              $old_date = date('y-m-d-h-i-s'); // works

                              $out = explode('-', $old_date);
                              $time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);

                              $new_date = date('Y-m-d H:i:s', $time);





                              share|improve this answer















                              $old_date = date('y-m-d-h-i-s'); // works


                              you are doing wrong here, this should be



                              $old_date = date('y-m-d h:i:s'); // works


                              separator of time is ':'




                              I think this will help...



                              $old_date = date('y-m-d-h-i-s'); // works

                              preg_match_all('/(d+)-(d+)-(d+)-(d+)-(d+)-(d+)/', $old_date, $out, PREG_SET_ORDER);
                              $out = $out[0];
                              $time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);

                              $new_date = date('Y-m-d H:i:s', $time);


                              OR




                              $old_date = date('y-m-d-h-i-s'); // works

                              $out = explode('-', $old_date);
                              $time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);

                              $new_date = date('Y-m-d H:i:s', $time);






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jan 30 '10 at 15:13

























                              answered Jan 30 '10 at 13:08









                              RifatRifat

                              6,60542443




                              6,60542443












                              • Yes, sure thanks, it's a GUID filename that I want to convert back into a proper date format.

                                – Tom
                                Jan 30 '10 at 13:11

















                              • Yes, sure thanks, it's a GUID filename that I want to convert back into a proper date format.

                                – Tom
                                Jan 30 '10 at 13:11
















                              Yes, sure thanks, it's a GUID filename that I want to convert back into a proper date format.

                              – Tom
                              Jan 30 '10 at 13:11





                              Yes, sure thanks, it's a GUID filename that I want to convert back into a proper date format.

                              – Tom
                              Jan 30 '10 at 13:11











                              9














                              The following is an easy method to convert dates to different formats.



                              // Create a new DateTime object
                              $date = DateTime::createFromFormat('Y-m-d', '2016-03-25');

                              // Output the date in different formats
                              echo $date->format('Y-m-d')."n";
                              echo $date->format('d-m-Y')."n";
                              echo $date->format('m-d-Y')."n";





                              share|improve this answer





























                                9














                                The following is an easy method to convert dates to different formats.



                                // Create a new DateTime object
                                $date = DateTime::createFromFormat('Y-m-d', '2016-03-25');

                                // Output the date in different formats
                                echo $date->format('Y-m-d')."n";
                                echo $date->format('d-m-Y')."n";
                                echo $date->format('m-d-Y')."n";





                                share|improve this answer



























                                  9












                                  9








                                  9







                                  The following is an easy method to convert dates to different formats.



                                  // Create a new DateTime object
                                  $date = DateTime::createFromFormat('Y-m-d', '2016-03-25');

                                  // Output the date in different formats
                                  echo $date->format('Y-m-d')."n";
                                  echo $date->format('d-m-Y')."n";
                                  echo $date->format('m-d-Y')."n";





                                  share|improve this answer















                                  The following is an easy method to convert dates to different formats.



                                  // Create a new DateTime object
                                  $date = DateTime::createFromFormat('Y-m-d', '2016-03-25');

                                  // Output the date in different formats
                                  echo $date->format('Y-m-d')."n";
                                  echo $date->format('d-m-Y')."n";
                                  echo $date->format('m-d-Y')."n";






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jan 19 '18 at 7:09

























                                  answered Mar 25 '16 at 9:11









                                  PeterPeter

                                  4,50043772




                                  4,50043772





















                                      6














                                      You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.






                                      share|improve this answer



























                                        6














                                        You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.






                                        share|improve this answer

























                                          6












                                          6








                                          6







                                          You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.






                                          share|improve this answer













                                          You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jan 30 '10 at 13:01









                                          John ParkerJohn Parker

                                          48.6k10111119




                                          48.6k10111119





















                                              6














                                              strtotime will work that out. the dates are just not the same and all in us-format.



                                              <?php
                                              $e1 = strtotime("2013-07-22T12:00:03Z");
                                              echo date('y.m.d H:i', $e1);
                                              echo "2013-07-22T12:00:03Z";

                                              $e2 = strtotime("2013-07-23T18:18:15Z");
                                              echo date ('y.m.d H:i', $e2);
                                              echo "2013-07-23T18:18:15Z";

                                              $e1 = strtotime("2013-07-21T23:57:04Z");
                                              echo date ('y.m.d H:i', $e2);
                                              echo "2013-07-21T23:57:04Z";
                                              ?>





                                              share|improve this answer



























                                                6














                                                strtotime will work that out. the dates are just not the same and all in us-format.



                                                <?php
                                                $e1 = strtotime("2013-07-22T12:00:03Z");
                                                echo date('y.m.d H:i', $e1);
                                                echo "2013-07-22T12:00:03Z";

                                                $e2 = strtotime("2013-07-23T18:18:15Z");
                                                echo date ('y.m.d H:i', $e2);
                                                echo "2013-07-23T18:18:15Z";

                                                $e1 = strtotime("2013-07-21T23:57:04Z");
                                                echo date ('y.m.d H:i', $e2);
                                                echo "2013-07-21T23:57:04Z";
                                                ?>





                                                share|improve this answer

























                                                  6












                                                  6








                                                  6







                                                  strtotime will work that out. the dates are just not the same and all in us-format.



                                                  <?php
                                                  $e1 = strtotime("2013-07-22T12:00:03Z");
                                                  echo date('y.m.d H:i', $e1);
                                                  echo "2013-07-22T12:00:03Z";

                                                  $e2 = strtotime("2013-07-23T18:18:15Z");
                                                  echo date ('y.m.d H:i', $e2);
                                                  echo "2013-07-23T18:18:15Z";

                                                  $e1 = strtotime("2013-07-21T23:57:04Z");
                                                  echo date ('y.m.d H:i', $e2);
                                                  echo "2013-07-21T23:57:04Z";
                                                  ?>





                                                  share|improve this answer













                                                  strtotime will work that out. the dates are just not the same and all in us-format.



                                                  <?php
                                                  $e1 = strtotime("2013-07-22T12:00:03Z");
                                                  echo date('y.m.d H:i', $e1);
                                                  echo "2013-07-22T12:00:03Z";

                                                  $e2 = strtotime("2013-07-23T18:18:15Z");
                                                  echo date ('y.m.d H:i', $e2);
                                                  echo "2013-07-23T18:18:15Z";

                                                  $e1 = strtotime("2013-07-21T23:57:04Z");
                                                  echo date ('y.m.d H:i', $e2);
                                                  echo "2013-07-21T23:57:04Z";
                                                  ?>






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jul 23 '13 at 21:10









                                                  de_nuitde_nuit

                                                  496612




                                                  496612





















                                                      4














                                                      Try this:



                                                      $tempDate = explode('-','03-23-15');
                                                      $date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];





                                                      share|improve this answer





























                                                        4














                                                        Try this:



                                                        $tempDate = explode('-','03-23-15');
                                                        $date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];





                                                        share|improve this answer



























                                                          4












                                                          4








                                                          4







                                                          Try this:



                                                          $tempDate = explode('-','03-23-15');
                                                          $date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];





                                                          share|improve this answer















                                                          Try this:



                                                          $tempDate = explode('-','03-23-15');
                                                          $date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jun 6 '17 at 7:36









                                                          Pang

                                                          6,9391664102




                                                          6,9391664102










                                                          answered Mar 31 '15 at 13:06









                                                          vineetvineet

                                                          6,42934257




                                                          6,42934257





















                                                              4














                                                              This native way will help to convert any inputted format to the desired format.



                                                              $formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
                                                              $dateInput = '01-02-2018'; //date in above format

                                                              $formatOut = 'Y-m-d'; // Your format
                                                              $dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);





                                                              share|improve this answer



























                                                                4














                                                                This native way will help to convert any inputted format to the desired format.



                                                                $formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
                                                                $dateInput = '01-02-2018'; //date in above format

                                                                $formatOut = 'Y-m-d'; // Your format
                                                                $dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);





                                                                share|improve this answer

























                                                                  4












                                                                  4








                                                                  4







                                                                  This native way will help to convert any inputted format to the desired format.



                                                                  $formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
                                                                  $dateInput = '01-02-2018'; //date in above format

                                                                  $formatOut = 'Y-m-d'; // Your format
                                                                  $dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);





                                                                  share|improve this answer













                                                                  This native way will help to convert any inputted format to the desired format.



                                                                  $formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
                                                                  $dateInput = '01-02-2018'; //date in above format

                                                                  $formatOut = 'Y-m-d'; // Your format
                                                                  $dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Feb 7 '18 at 8:38









                                                                  Nishad UpNishad Up

                                                                  1,7101223




                                                                  1,7101223





















                                                                      4














                                                                      This solved for me,



                                                                      $old = '18-04-2018';
                                                                      $new = date('Y-m-d', strtotime($old));
                                                                      echo $new;


                                                                      Output : 2018-04-18






                                                                      share|improve this answer



























                                                                        4














                                                                        This solved for me,



                                                                        $old = '18-04-2018';
                                                                        $new = date('Y-m-d', strtotime($old));
                                                                        echo $new;


                                                                        Output : 2018-04-18






                                                                        share|improve this answer

























                                                                          4












                                                                          4








                                                                          4







                                                                          This solved for me,



                                                                          $old = '18-04-2018';
                                                                          $new = date('Y-m-d', strtotime($old));
                                                                          echo $new;


                                                                          Output : 2018-04-18






                                                                          share|improve this answer













                                                                          This solved for me,



                                                                          $old = '18-04-2018';
                                                                          $new = date('Y-m-d', strtotime($old));
                                                                          echo $new;


                                                                          Output : 2018-04-18







                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Apr 4 '18 at 18:34









                                                                          Arthi RajgopalArthi Rajgopal

                                                                          330517




                                                                          330517





















                                                                              1














                                                                              This is the other way you can convert date format



                                                                               <?php
                                                                              $pastDate = "Tuesday 11th October, 2016";
                                                                              $pastDate = str_replace(",","",$pastDate);

                                                                              $date = new DateTime($pastDate);
                                                                              $new_date_format = $date->format('Y-m-d');

                                                                              echo $new_date_format.' 23:59:59'; ?>





                                                                              share|improve this answer



























                                                                                1














                                                                                This is the other way you can convert date format



                                                                                 <?php
                                                                                $pastDate = "Tuesday 11th October, 2016";
                                                                                $pastDate = str_replace(",","",$pastDate);

                                                                                $date = new DateTime($pastDate);
                                                                                $new_date_format = $date->format('Y-m-d');

                                                                                echo $new_date_format.' 23:59:59'; ?>





                                                                                share|improve this answer

























                                                                                  1












                                                                                  1








                                                                                  1







                                                                                  This is the other way you can convert date format



                                                                                   <?php
                                                                                  $pastDate = "Tuesday 11th October, 2016";
                                                                                  $pastDate = str_replace(",","",$pastDate);

                                                                                  $date = new DateTime($pastDate);
                                                                                  $new_date_format = $date->format('Y-m-d');

                                                                                  echo $new_date_format.' 23:59:59'; ?>





                                                                                  share|improve this answer













                                                                                  This is the other way you can convert date format



                                                                                   <?php
                                                                                  $pastDate = "Tuesday 11th October, 2016";
                                                                                  $pastDate = str_replace(",","",$pastDate);

                                                                                  $date = new DateTime($pastDate);
                                                                                  $new_date_format = $date->format('Y-m-d');

                                                                                  echo $new_date_format.' 23:59:59'; ?>






                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Jun 6 '17 at 7:22









                                                                                  Varun MalhotraVarun Malhotra

                                                                                  81031121




                                                                                  81031121





















                                                                                      0














                                                                                      Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.



                                                                                      class dateTranslator {

                                                                                      public static function translate($date, $lang)
                                                                                      $divider = '';

                                                                                      if (empty($date))
                                                                                      return null;

                                                                                      if (strpos($date, '-') !== false)
                                                                                      $divider = '-';
                                                                                      else if (strpos($date, '/') !== false)
                                                                                      $divider = '/';

                                                                                      //spanish format DD/MM/YYYY hh:mm
                                                                                      if (strcmp($lang, 'es') == 0)

                                                                                      $type = explode($divider, $date)[0];
                                                                                      if (strlen($type) == 4)
                                                                                      $date = self::reverseDate($date,$divider);

                                                                                      if (strcmp($divider, '-') == 0)
                                                                                      $date = str_replace("-", "/", $date);

                                                                                      //english format YYYY-MM-DD hh:mm
                                                                                      else

                                                                                      $type = explode($divider, $date)[0];
                                                                                      if (strlen($type) == 2)

                                                                                      $date = self::reverseDate($date,$divider);

                                                                                      if (strcmp($divider, '/') == 0)
                                                                                      $date = str_replace("/", "-", $date);



                                                                                      return $date;


                                                                                      public static function reverseDate($date)
                                                                                      $date2 = explode(' ', $date);
                                                                                      if (count($date2) == 2)
                                                                                      $date = implode("-", array_reverse(preg_split("/D/", $date2[0]))) . ' ' . $date2[1];
                                                                                      else
                                                                                      $date = implode("-", array_reverse(preg_split("/D/", $date)));


                                                                                      return $date;



                                                                                      USE



                                                                                      dateTranslator::translate($date, 'en')





                                                                                      share|improve this answer





























                                                                                        0














                                                                                        Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.



                                                                                        class dateTranslator {

                                                                                        public static function translate($date, $lang)
                                                                                        $divider = '';

                                                                                        if (empty($date))
                                                                                        return null;

                                                                                        if (strpos($date, '-') !== false)
                                                                                        $divider = '-';
                                                                                        else if (strpos($date, '/') !== false)
                                                                                        $divider = '/';

                                                                                        //spanish format DD/MM/YYYY hh:mm
                                                                                        if (strcmp($lang, 'es') == 0)

                                                                                        $type = explode($divider, $date)[0];
                                                                                        if (strlen($type) == 4)
                                                                                        $date = self::reverseDate($date,$divider);

                                                                                        if (strcmp($divider, '-') == 0)
                                                                                        $date = str_replace("-", "/", $date);

                                                                                        //english format YYYY-MM-DD hh:mm
                                                                                        else

                                                                                        $type = explode($divider, $date)[0];
                                                                                        if (strlen($type) == 2)

                                                                                        $date = self::reverseDate($date,$divider);

                                                                                        if (strcmp($divider, '/') == 0)
                                                                                        $date = str_replace("/", "-", $date);



                                                                                        return $date;


                                                                                        public static function reverseDate($date)
                                                                                        $date2 = explode(' ', $date);
                                                                                        if (count($date2) == 2)
                                                                                        $date = implode("-", array_reverse(preg_split("/D/", $date2[0]))) . ' ' . $date2[1];
                                                                                        else
                                                                                        $date = implode("-", array_reverse(preg_split("/D/", $date)));


                                                                                        return $date;



                                                                                        USE



                                                                                        dateTranslator::translate($date, 'en')





                                                                                        share|improve this answer



























                                                                                          0












                                                                                          0








                                                                                          0







                                                                                          Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.



                                                                                          class dateTranslator {

                                                                                          public static function translate($date, $lang)
                                                                                          $divider = '';

                                                                                          if (empty($date))
                                                                                          return null;

                                                                                          if (strpos($date, '-') !== false)
                                                                                          $divider = '-';
                                                                                          else if (strpos($date, '/') !== false)
                                                                                          $divider = '/';

                                                                                          //spanish format DD/MM/YYYY hh:mm
                                                                                          if (strcmp($lang, 'es') == 0)

                                                                                          $type = explode($divider, $date)[0];
                                                                                          if (strlen($type) == 4)
                                                                                          $date = self::reverseDate($date,$divider);

                                                                                          if (strcmp($divider, '-') == 0)
                                                                                          $date = str_replace("-", "/", $date);

                                                                                          //english format YYYY-MM-DD hh:mm
                                                                                          else

                                                                                          $type = explode($divider, $date)[0];
                                                                                          if (strlen($type) == 2)

                                                                                          $date = self::reverseDate($date,$divider);

                                                                                          if (strcmp($divider, '/') == 0)
                                                                                          $date = str_replace("/", "-", $date);



                                                                                          return $date;


                                                                                          public static function reverseDate($date)
                                                                                          $date2 = explode(' ', $date);
                                                                                          if (count($date2) == 2)
                                                                                          $date = implode("-", array_reverse(preg_split("/D/", $date2[0]))) . ' ' . $date2[1];
                                                                                          else
                                                                                          $date = implode("-", array_reverse(preg_split("/D/", $date)));


                                                                                          return $date;



                                                                                          USE



                                                                                          dateTranslator::translate($date, 'en')





                                                                                          share|improve this answer















                                                                                          Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.



                                                                                          class dateTranslator {

                                                                                          public static function translate($date, $lang)
                                                                                          $divider = '';

                                                                                          if (empty($date))
                                                                                          return null;

                                                                                          if (strpos($date, '-') !== false)
                                                                                          $divider = '-';
                                                                                          else if (strpos($date, '/') !== false)
                                                                                          $divider = '/';

                                                                                          //spanish format DD/MM/YYYY hh:mm
                                                                                          if (strcmp($lang, 'es') == 0)

                                                                                          $type = explode($divider, $date)[0];
                                                                                          if (strlen($type) == 4)
                                                                                          $date = self::reverseDate($date,$divider);

                                                                                          if (strcmp($divider, '-') == 0)
                                                                                          $date = str_replace("-", "/", $date);

                                                                                          //english format YYYY-MM-DD hh:mm
                                                                                          else

                                                                                          $type = explode($divider, $date)[0];
                                                                                          if (strlen($type) == 2)

                                                                                          $date = self::reverseDate($date,$divider);

                                                                                          if (strcmp($divider, '/') == 0)
                                                                                          $date = str_replace("/", "-", $date);



                                                                                          return $date;


                                                                                          public static function reverseDate($date)
                                                                                          $date2 = explode(' ', $date);
                                                                                          if (count($date2) == 2)
                                                                                          $date = implode("-", array_reverse(preg_split("/D/", $date2[0]))) . ' ' . $date2[1];
                                                                                          else
                                                                                          $date = implode("-", array_reverse(preg_split("/D/", $date)));


                                                                                          return $date;



                                                                                          USE



                                                                                          dateTranslator::translate($date, 'en')






                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited Sep 1 '17 at 8:02

























                                                                                          answered Nov 30 '16 at 20:58









                                                                                          Alejandro ArandaAlejandro Aranda

                                                                                          372410




                                                                                          372410





















                                                                                              0














                                                                                              I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.



                                                                                              This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.



                                                                                              To call it:



                                                                                              $TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);


                                                                                              Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).



                                                                                              Here's the code:



                                                                                               <?php 
                                                                                              function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)

                                                                                              if (!isset($dttm))

                                                                                              return "";

                                                                                              $timepieces = array();
                                                                                              if (is_numeric($dttm))

                                                                                              $rettime=$dttm;

                                                                                              else

                                                                                              $rettime=strtotime($dttm);
                                                                                              if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)

                                                                                              $rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
                                                                                              $timepieces[1]="";

                                                                                              else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)

                                                                                              preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
                                                                                              $rettime=$rettime.".".$timepieces[1];



                                                                                              if (isset($dtFormat))

                                                                                              // RETURN as ANY date format sent
                                                                                              if (strpos($dtFormat,".u")>0) // Deal with milliseconds

                                                                                              $rettime=date($dtFormat,$rettime);
                                                                                              $rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];

                                                                                              else // NO milliseconds wanted

                                                                                              $rettime=date($dtFormat,$rettime);


                                                                                              else

                                                                                              // RETURN Epoch Time (do nothing, we already built Epoch Time)

                                                                                              return $rettime;

                                                                                              ?>


                                                                                              Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).



                                                                                               $utctime1="2018-10-30T06:10:11.2185007-07:00";
                                                                                              $utctime2="2018-10-30T06:10:11.2185007";
                                                                                              $utctime3="2018-10-30T06:10:11.2185007 PDT";
                                                                                              $utctime4="2018-10-30T13:10:11.2185007Z";
                                                                                              $utctime5="2018-10-30T13:10:11Z";
                                                                                              $dttm="10/30/2018 09:10:11 AM EST";

                                                                                              echo "<pre>";
                                                                                              echo "<b>Epoch Time to a standard format</b><br>";
                                                                                              echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
                                                                                              echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
                                                                                              echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
                                                                                              echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
                                                                                              echo "</b><br>";
                                                                                              echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
                                                                                              echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
                                                                                              echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
                                                                                              echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
                                                                                              echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
                                                                                              echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
                                                                                              echo "<hr>";
                                                                                              echo "<hr>";
                                                                                              echo "<b>Returned as whatever datetime format one desires</b>";
                                                                                              echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
                                                                                              echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                              echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                              echo "<p><b>Returned as ISO8601</b>";
                                                                                              echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
                                                                                              echo "</pre>";


                                                                                              Here's the output:



                                                                                              Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11

                                                                                              Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                              Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                              Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)

                                                                                              UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
                                                                                              UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
                                                                                              UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
                                                                                              UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
                                                                                              UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
                                                                                              NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
                                                                                              Returned as whatever datetime format one desires
                                                                                              UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
                                                                                              UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
                                                                                              UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
                                                                                              Returned as ISO8601
                                                                                              UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601


                                                                                              The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.






                                                                                              share|improve this answer



























                                                                                                0














                                                                                                I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.



                                                                                                This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.



                                                                                                To call it:



                                                                                                $TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);


                                                                                                Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).



                                                                                                Here's the code:



                                                                                                 <?php 
                                                                                                function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)

                                                                                                if (!isset($dttm))

                                                                                                return "";

                                                                                                $timepieces = array();
                                                                                                if (is_numeric($dttm))

                                                                                                $rettime=$dttm;

                                                                                                else

                                                                                                $rettime=strtotime($dttm);
                                                                                                if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)

                                                                                                $rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
                                                                                                $timepieces[1]="";

                                                                                                else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)

                                                                                                preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
                                                                                                $rettime=$rettime.".".$timepieces[1];



                                                                                                if (isset($dtFormat))

                                                                                                // RETURN as ANY date format sent
                                                                                                if (strpos($dtFormat,".u")>0) // Deal with milliseconds

                                                                                                $rettime=date($dtFormat,$rettime);
                                                                                                $rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];

                                                                                                else // NO milliseconds wanted

                                                                                                $rettime=date($dtFormat,$rettime);


                                                                                                else

                                                                                                // RETURN Epoch Time (do nothing, we already built Epoch Time)

                                                                                                return $rettime;

                                                                                                ?>


                                                                                                Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).



                                                                                                 $utctime1="2018-10-30T06:10:11.2185007-07:00";
                                                                                                $utctime2="2018-10-30T06:10:11.2185007";
                                                                                                $utctime3="2018-10-30T06:10:11.2185007 PDT";
                                                                                                $utctime4="2018-10-30T13:10:11.2185007Z";
                                                                                                $utctime5="2018-10-30T13:10:11Z";
                                                                                                $dttm="10/30/2018 09:10:11 AM EST";

                                                                                                echo "<pre>";
                                                                                                echo "<b>Epoch Time to a standard format</b><br>";
                                                                                                echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
                                                                                                echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
                                                                                                echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
                                                                                                echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
                                                                                                echo "</b><br>";
                                                                                                echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
                                                                                                echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
                                                                                                echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
                                                                                                echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
                                                                                                echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
                                                                                                echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
                                                                                                echo "<hr>";
                                                                                                echo "<hr>";
                                                                                                echo "<b>Returned as whatever datetime format one desires</b>";
                                                                                                echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
                                                                                                echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                                echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                                echo "<p><b>Returned as ISO8601</b>";
                                                                                                echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
                                                                                                echo "</pre>";


                                                                                                Here's the output:



                                                                                                Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11

                                                                                                Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                                Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                                Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)

                                                                                                UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
                                                                                                UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
                                                                                                UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
                                                                                                UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
                                                                                                UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
                                                                                                NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
                                                                                                Returned as whatever datetime format one desires
                                                                                                UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
                                                                                                UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
                                                                                                UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
                                                                                                Returned as ISO8601
                                                                                                UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601


                                                                                                The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.






                                                                                                share|improve this answer

























                                                                                                  0












                                                                                                  0








                                                                                                  0







                                                                                                  I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.



                                                                                                  This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.



                                                                                                  To call it:



                                                                                                  $TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);


                                                                                                  Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).



                                                                                                  Here's the code:



                                                                                                   <?php 
                                                                                                  function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)

                                                                                                  if (!isset($dttm))

                                                                                                  return "";

                                                                                                  $timepieces = array();
                                                                                                  if (is_numeric($dttm))

                                                                                                  $rettime=$dttm;

                                                                                                  else

                                                                                                  $rettime=strtotime($dttm);
                                                                                                  if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)

                                                                                                  $rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
                                                                                                  $timepieces[1]="";

                                                                                                  else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)

                                                                                                  preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
                                                                                                  $rettime=$rettime.".".$timepieces[1];



                                                                                                  if (isset($dtFormat))

                                                                                                  // RETURN as ANY date format sent
                                                                                                  if (strpos($dtFormat,".u")>0) // Deal with milliseconds

                                                                                                  $rettime=date($dtFormat,$rettime);
                                                                                                  $rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];

                                                                                                  else // NO milliseconds wanted

                                                                                                  $rettime=date($dtFormat,$rettime);


                                                                                                  else

                                                                                                  // RETURN Epoch Time (do nothing, we already built Epoch Time)

                                                                                                  return $rettime;

                                                                                                  ?>


                                                                                                  Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).



                                                                                                   $utctime1="2018-10-30T06:10:11.2185007-07:00";
                                                                                                  $utctime2="2018-10-30T06:10:11.2185007";
                                                                                                  $utctime3="2018-10-30T06:10:11.2185007 PDT";
                                                                                                  $utctime4="2018-10-30T13:10:11.2185007Z";
                                                                                                  $utctime5="2018-10-30T13:10:11Z";
                                                                                                  $dttm="10/30/2018 09:10:11 AM EST";

                                                                                                  echo "<pre>";
                                                                                                  echo "<b>Epoch Time to a standard format</b><br>";
                                                                                                  echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
                                                                                                  echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
                                                                                                  echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
                                                                                                  echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
                                                                                                  echo "</b><br>";
                                                                                                  echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
                                                                                                  echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
                                                                                                  echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
                                                                                                  echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
                                                                                                  echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
                                                                                                  echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
                                                                                                  echo "<hr>";
                                                                                                  echo "<hr>";
                                                                                                  echo "<b>Returned as whatever datetime format one desires</b>";
                                                                                                  echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
                                                                                                  echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                                  echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                                  echo "<p><b>Returned as ISO8601</b>";
                                                                                                  echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
                                                                                                  echo "</pre>";


                                                                                                  Here's the output:



                                                                                                  Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11

                                                                                                  Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                                  Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                                  Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)

                                                                                                  UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
                                                                                                  UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
                                                                                                  UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
                                                                                                  UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
                                                                                                  UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
                                                                                                  NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
                                                                                                  Returned as whatever datetime format one desires
                                                                                                  UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
                                                                                                  UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
                                                                                                  UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
                                                                                                  Returned as ISO8601
                                                                                                  UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601


                                                                                                  The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.






                                                                                                  share|improve this answer













                                                                                                  I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.



                                                                                                  This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.



                                                                                                  To call it:



                                                                                                  $TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);


                                                                                                  Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).



                                                                                                  Here's the code:



                                                                                                   <?php 
                                                                                                  function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)

                                                                                                  if (!isset($dttm))

                                                                                                  return "";

                                                                                                  $timepieces = array();
                                                                                                  if (is_numeric($dttm))

                                                                                                  $rettime=$dttm;

                                                                                                  else

                                                                                                  $rettime=strtotime($dttm);
                                                                                                  if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)

                                                                                                  $rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
                                                                                                  $timepieces[1]="";

                                                                                                  else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)

                                                                                                  preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
                                                                                                  $rettime=$rettime.".".$timepieces[1];



                                                                                                  if (isset($dtFormat))

                                                                                                  // RETURN as ANY date format sent
                                                                                                  if (strpos($dtFormat,".u")>0) // Deal with milliseconds

                                                                                                  $rettime=date($dtFormat,$rettime);
                                                                                                  $rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];

                                                                                                  else // NO milliseconds wanted

                                                                                                  $rettime=date($dtFormat,$rettime);


                                                                                                  else

                                                                                                  // RETURN Epoch Time (do nothing, we already built Epoch Time)

                                                                                                  return $rettime;

                                                                                                  ?>


                                                                                                  Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).



                                                                                                   $utctime1="2018-10-30T06:10:11.2185007-07:00";
                                                                                                  $utctime2="2018-10-30T06:10:11.2185007";
                                                                                                  $utctime3="2018-10-30T06:10:11.2185007 PDT";
                                                                                                  $utctime4="2018-10-30T13:10:11.2185007Z";
                                                                                                  $utctime5="2018-10-30T13:10:11Z";
                                                                                                  $dttm="10/30/2018 09:10:11 AM EST";

                                                                                                  echo "<pre>";
                                                                                                  echo "<b>Epoch Time to a standard format</b><br>";
                                                                                                  echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
                                                                                                  echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
                                                                                                  echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
                                                                                                  echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
                                                                                                  echo "</b><br>";
                                                                                                  echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
                                                                                                  echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
                                                                                                  echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
                                                                                                  echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
                                                                                                  echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
                                                                                                  echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
                                                                                                  echo "<hr>";
                                                                                                  echo "<hr>";
                                                                                                  echo "<b>Returned as whatever datetime format one desires</b>";
                                                                                                  echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
                                                                                                  echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                                  echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
                                                                                                  echo "<p><b>Returned as ISO8601</b>";
                                                                                                  echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
                                                                                                  echo "</pre>";


                                                                                                  Here's the output:



                                                                                                  Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11

                                                                                                  Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                                  Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
                                                                                                  Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)

                                                                                                  UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
                                                                                                  UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
                                                                                                  UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
                                                                                                  UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
                                                                                                  UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
                                                                                                  NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
                                                                                                  Returned as whatever datetime format one desires
                                                                                                  UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
                                                                                                  UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
                                                                                                  UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
                                                                                                  Returned as ISO8601
                                                                                                  UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601


                                                                                                  The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Feb 1 at 20:34









                                                                                                  Robert MauroRobert Mauro

                                                                                                  12519




                                                                                                  12519















                                                                                                      protected by Community Feb 3 '14 at 16:31



                                                                                                      Thank you for your interest in this question.
                                                                                                      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                      Would you like to answer one of these unanswered questions instead?



                                                                                                      Popular posts from this blog

                                                                                                      How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                                                                                                      Syphilis

                                                                                                      Darth Vader #20