I have a datetime field in a SQL Server 2005 table that has values like this:
2012-04-23 09:00:00.000
2012-04-23 14:00:00.000
The minutes, seconds, and microseconds are always zero.
I need to display a “time slot” (basically, the time plus one hour) like this:
2012/04/23 09:00 AM - 10:00 AM
2012/04/23 02:00 PM - 03:00 PM
I got what I needed using this:
SELECT SUBSTRING(CONVERT(VARCHAR, TimeSlot, 20), 1, 10) + ' ' +
RIGHT('00000' + LTRIM(SUBSTRING(CONVERT(VARCHAR(24), TimeSlot, 109), 13, 5)), 5) + ' ' +
SUBSTRING(CONVERT(VARCHAR(19), TimeSlot, 100),18,2) + ' - ' +
RIGHT('00000' + LTRIM(SUBSTRING(CONVERT(VARCHAR(24), DATEADD(hh, 1, TimeSlot), 109), 13, 5)), 5) + ' ' +
SUBSTRING(CONVERT(VARCHAR(19), DATEADD(hh, 1, TimeSlot), 100), 18, 2) AS TimeSlot
FROM MyTable
It works, but I feel so dirty.
I know I could do it easier in the code (VB .NET), but assume I have to do it in SQL.
Is there any cleaner way to do this?
Taking the built-in conversions, I would use something like this:
this gives you the line you want as
in detail:
convert(varchar, @dt, 111)converts thedatetimeto the Japanese formatyy/mm/ddconvert(varchar, @dt, 0)converts thedatetimetoApr 23 2012 9:00AMso we can use the time partdateadd(hour, 1, @dt)adds one hour to the currentdatetimevalueyou can test it without tables with: