Time part of a DateTime Field in SQL

后端 未结 11 1679
小蘑菇
小蘑菇 2020-12-03 04:39

How would I be able to extract the time part of a DateTime field in SQL? For my project I have to return data that has a timestamp of 5pm of a DateTime field no matter what

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 05:07

    This will return the time-Only

    For SQL Server:

    SELECT convert(varchar(8), getdate(), 108)
    

    Explanation:

    getDate() is giving current date and time.
    108 is formatting/giving us the required portion i.e time in this case.
    varchar(8) gives us the number of characters from that portion.
    Like:
    If you wrote varchar(7) there, it will give you 00:00:0
    If you wrote varchar(6) there, it will give you 00:00:
    If you wrote varchar(15) there, it will still give you 00:00:00 because it is giving output of just time portion. SQLFiddle Demo

    For MySQL:

    SELECT DATE_FORMAT(NOW(), '%H:%i:%s')
    

    SQLFiddle Demo

提交回复
热议问题