SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Location
    Porto,Portugal
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Convert php date to mysql datetime format

    Hi.
    I have a date in the following format: dd/mm/YYYY.
    I need to convert it to mysql dateTime. (Y-m-d H:i:s)

    I have tried a couple of php date functions but i cant get them to work.

    Can someone help me?

  2. #2
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    71 Post(s)
    Tagged
    0 Thread(s)
    Keep in mind that MySQL comes with a NOW() function in it's query structure for inserting the current dateTime.

    Assuming your current input is not NOW() (or time()), strtotime() the date, and then feed the result into date() as the second parameter.

    PHP Code:
    $date date("Y-m-d H:i:s",strtotime($date)) 

  3. #3
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Location
    Porto,Portugal
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok i tried that function and it works but now i have a problem.

    Lets say i have the date 06/04/2010 in dd/mm/yyyy format. It should be converted to 2010-04-06 (yyyy-mm-dd) but it is converted into 2010-06-04 (yyyy-dd-mm).

  4. #4
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    71 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Popovich88 View Post
    Ok i tried that function and it works but now i have a problem.

    Lets say i have the date 06/04/2010 in dd/mm/yyyy format. It should be converted to 2010-04-06 (yyyy-mm-dd) but it is converted into 2010-06-04 (yyyy-dd-mm).
    Transform the data into the proper format. The date you give is assumed to be in mm/dd/yyyy format, because PHP is written in the US.

    If you -know- for certain that your dates will always be in dd/mm/yyyy format, try transforming it this way:

    PHP Code:
    $date date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date))) 
    strtotime interprets x/y/z as mm/dd/yy[yy], and x-y-z as dd-mm-yyyy or yy-mm-dd, depending on whether z is 4 digits or 2.

  5. #5
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Location
    Porto,Portugal
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great.
    It works now


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •