Extracting hours from a DateTime (SQL Server 2005)

后端 未结 11 502
野趣味
野趣味 2020-12-01 03:21

I can extract the month and day by using Day(Date()), Month(Date()). I can\'t extract hours, with HOUR(Date()). I get the following er

相关标签:
11条回答
  • 2020-12-01 03:54

    DATEPART(HOUR, [date]) returns the hour in military time ( 00 to 23 ) If you want 1AM, 3PM etc, you need to case it out:

    SELECT Run_Time_Hour =
    CASE DATEPART(HOUR, R.date_schedule)
        WHEN 0 THEN  '12AM'
        WHEN 1 THEN   '1AM'
        WHEN 2 THEN   '2AM'
        WHEN 3 THEN   '3AM'
        WHEN 4 THEN   '4AM'
        WHEN 5 THEN   '5AM'
        WHEN 6 THEN   '6AM'
        WHEN 7 THEN   '7AM'
        WHEN 8 THEN   '8AM'
        WHEN 9 THEN   '9AM'
        WHEN 10 THEN '10AM'
        WHEN 11 THEN '11AM'
        WHEN 12 THEN '12PM'
        ELSE CONVERT(varchar, DATEPART(HOUR, R.date_schedule)-12) + 'PM'
    END
    FROM
        dbo.ARCHIVE_RUN_SCHEDULE R
    
    0 讨论(0)
  • 2020-12-01 04:01
    SELECT DATEPART(HOUR, GETDATE());
    

    DATEPART documentation

    0 讨论(0)
  • 2020-12-01 04:01

    ... you can use it on any granularity type i.e.:

    DATEPART(YEAR, [date])
    
    DATEPART(MONTH, [date]) 
    
    DATEPART(DAY, [date])    
    
    DATEPART(HOUR, [date]) 
    
    DATEPART(MINUTE, [date])
    

    (note: I like the [ ] around the date reserved word though. Of course that's in case your column with timestamp is labeled "date")

    0 讨论(0)
  • 2020-12-01 04:01

    try this one too:

       DATEPART(HOUR,GETDATE()) 
    
    0 讨论(0)
  • 2020-12-01 04:01

    The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour, minute, etc.

    datepart    ***Abbreviation
    
    year        ***yy, yyyy 
    quarter     ***qq, q 
    month       ***mm, m 
    dayofyear   ***dy, y 
    day         ***dd, d 
    week        ***wk, ww 
    weekday     ***dw, w 
    hour        ***hh 
    minute      ***mi, n 
    second      ***ss, s 
    millisecond ***ms 
    microsecond ***mcs 
    nanosecond  ***ns 
    

    Example

    select * 
    from table001
    where datepart(hh,datetime) like 23
    
    0 讨论(0)
提交回复
热议问题