How can I convert String to DateTime in PHP?

Discussion in 'PHP' started by benjib98, Jan 4, 2008.

  1. #1
    Hi,

    Is there any possibility to do a type casting into datetime in PHP? I need to convert a string datetime format into a valid datetime. I read in the manual that date_create() takes a string to create a date, but not sure if this is the correct way - anyone to advice?
    Thanks
    Ben
     
    benjib98, Jan 4, 2008 IP
  2. ngcoders

    ngcoders Active Member

    Messages:
    206
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    55
    #2
    strtotime("your date time string"); will do the trick in most cases.
     
    ngcoders, Jan 4, 2008 IP
  3. benjib98

    benjib98 Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    ngcoders,
    correct me if I am wrong, but is not the strtotime() function returning an integer form of the time?
    I need to return a valid DateTime from the string input.
    Ben
     
    benjib98, Jan 4, 2008 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    date_create() accepts the value returned by strtotime() as parameter.
     
    nico_swd, Jan 4, 2008 IP
  5. benjib98

    benjib98 Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    just forgot to mention, that I am using PHP 4, so it should be compatible with this version. So date_create() cannot be used.
    Can I then use this way?

    $dtValidDateTime;
    $szDate = '12/31/2007';
    try
    {
    $dtValidDateTime = new DateTime($szDate);
    }
    catch(Exception $e)
    {
    //do something
    }
     
    benjib98, Jan 4, 2008 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    nico_swd, Jan 4, 2008 IP
  7. benjib98

    benjib98 Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    well if it is up to me than I don't think too much about it, but unfortunately we need to support PHP 4, as some of our clients still use it.
    thanks nico_swd and all
    Ben
     
    benjib98, Jan 4, 2008 IP