SgDotNet
Singapore Professional .NET User Group -For Cool Developers

Converting varchar to datetime

Latest post 01-05-2008 11:43 AM by eric_tcp. 6 replies.
  • 12-26-2007 7:53 PM

    Converting varchar to datetime

    I have a field (column name : TimeSlot) )that contains value in HH:mm format (e.g 22:00).

    Anyone know how to make a combination such as '12/26/2007' and the field i mentioned above to make it useable in datediff function?

    I tried to select DateDiff(minute,'12/27/2007' + ' ' + TimeSlot, GetDate())

    It gave me wrong time boundaries between these 2 date.

    Pls advise.

  • 12-27-2007 10:46 AM In reply to

    • cruizer
    • Top 50 Contributor
    • Joined on 07-25-2007
    • Singapore
    • Posts 140

    Re: Converting varchar to datetime

    are you trying to do the conversion within SQL Server, or in the .NET space?

    if you're doing it in managed code, just convert your HH:mm string into a TimeSpan. Then convert your date string into a DateTime. Then .Add() the TimeSpan to your DateTime and you've got them combined into a new DateTime.

    http://devpinoy.org/blogs/cruizer
  • 12-27-2007 4:59 PM In reply to

    Re: Converting varchar to datetime

    Seeing that you used GETDATE(), I am assuming that you are trying to do this in SQL server. Here is how to do what you want:

    SELECT DATEDIFF(minute, CONVERT(smalldatetime, '12/26/2007' + ' ' + CONVERT(varchar, TimeSlot, 108)), GETDATE())
    where the style 108 obtains the hh:mm:ss of your TimeSlot value.

    If your TimeSlot value is stored as varchar(5), you do not have to convert it to a date before concatenation.

  • 12-28-2007 1:28 PM In reply to

    Re: Converting varchar to datetime

    Ok thanks it works.

     Another question is I have a field in a table is which contains datetime, how can i query out the date (without time behind) and distinct?

    If I Use

    SELECT DISTINCT CONVERT(varchar, ShowTime, 3) from table

    Where .............' Date comparison  here

    It works totally ok but when the column contains 1st of Jan, 1st of Jan will exist although the date is not in my date comparison.

    Pls help, thanks.

  • 12-28-2007 5:21 PM In reply to

    Re: Converting varchar to datetime

    Probably your date comparison is not formatted correctly. Perhaps you want to post a sample here?
  • 01-01-2008 11:10 AM In reply to

    • usoup
    • Top 50 Contributor
    • Joined on 12-06-2004
    • Central
    • Posts 79

    Re: Converting varchar to datetime

    Perhaps you want to take a look into my blog about date time conversion

    http://community.sgdotnet.org/blogs/usoup/archive/2007/10/26/Next-Datetime_2C00_-please.aspx

    -- Signed with Soup --
  • 01-05-2008 11:43 AM In reply to

    Re: Converting varchar to datetime

    I now solved my problem, thanks guys :)
Page 1 of 1 (7 items) | RSS
Copyright SgDotNet 2004-2008
Powered by Community Server (Commercial Edition), by Telligent Systems