Convert varchar to time

Discussion in 'MySQL' started by ahdsan, Feb 19, 2011.

  1. #1
    I have a varchar field which has data as 9.50 pm, 8.59 am, 2.50 pm,4.00 am......
    I want to sort this field in time format
    I tried cast(), convert() but not working.
    pls help me urgent!
     
    ahdsan, Feb 19, 2011 IP
  2. AstarothSolutions

    AstarothSolutions Peon

    Messages:
    2,680
    Likes Received:
    77
    Best Answers:
    0
    Trophy Points:
    0
  3. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #3
    I would recommend having a new column in which data is stored in proper time format.

    For quick solution, ordering by below may help.

    
    SELECT col1, col2, ..., coln FROM tbl_name WHERE condition ORDER BY STR_TO_DATE(varchar_field, IF(RIGHT(varchar_field, 2) = 'am', '%h.%i am', '%h.%i pm')) ASC
    
    Code (markup):
    NOTE: Above way may slow down the query, because of run time conversion and then ordering. Best would be to have a separate column with proper time data and then direct ordering on it.
     
    mastermunj, Feb 19, 2011 IP
  4. ahdsan

    ahdsan Member

    Messages:
    74
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    I tried your query
    SELECT * FROM test ORDER BY STR_TO_DATE( otime, IF( RIGHT( otime, 2 ) = 'am', '%h.%i am', '%h.%i pm' ) ) ASC LIMIT 0 , 30
    and it is showing
    8:20 PM
    9:50 AM
    8:00 AM
    7:20 PM
    5:00 PM
    6:15 AM
     
    ahdsan, Feb 20, 2011 IP
  5. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #5
    If you wish the converted value in result as well, then you might want to alter your query like this:

    
    SELECT *, STR_TO_DATE( otime, IF( RIGHT( otime, 2 ) = 'am', '%h.%i am', '%h.%i pm' ) ) AS otime_converted FROM test ORDER BY STR_TO_DATE( otime, IF( RIGHT( otime, 2 ) = 'am', '%h.%i am', '%h.%i pm' ) ) ASC LIMIT 0 , 30
    
    Code (markup):
     
    mastermunj, Feb 20, 2011 IP
  6. ahdsan

    ahdsan Member

    Messages:
    74
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #6
    This query is giving me all 'NULL'
     
    ahdsan, Feb 20, 2011 IP
  7. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #7
    If otime has values you mentioned, like 3.40 pm, 2.50 am, then above query should work proper. Does it have any space after text? In that case change RIGHT(otime, 2) with RIGHT(TRIM(otime), 2).
     
    mastermunj, Feb 23, 2011 IP