time format in SQL Server

前端 未结 7 1731
心在旅途
心在旅途 2020-12-04 01:20

Does anyone know how can I format a select statement datetime value to only display time in SQL Server?

example:

Table cuatomer
id   name   datetime
         


        
相关标签:
7条回答
  • 2020-12-04 01:56

    If you are using MySql you can use TIME_FORMAT()

    Code ↓↓

    SELECT name, time_format(datatime,'%H:%i') as tine from cuatomer
    
    0 讨论(0)
  • 2020-12-04 01:59

    If You are using SQL Server 2008 or Higher You can use the following statement:

    SELECT Convert( VarChar( 10 ), CAST([columnName] AS TIME(0)), 100 )
    
    0 讨论(0)
  • 2020-12-04 02:02

    You can use a combination of CONVERT, RIGHT and TRIM to get the desired result:

    SELECT ltrim(right(convert(varchar(25), getdate(), 100), 7))
    

    The 100 you see in the function specifies the date format mon dd yyyy hh:miAM (or PM), and from there we just grab the right characters.

    You can see more about converting datetimes here.

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

    This will get the time from a datetime value and also give the am or pm add on

    SELECT RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),8)),7) 
    

    will always return the date in HH:mmAM format.

    Note the lack of space

    Or

    SELECT REPLACE(REPLACE(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),7)),7),'AM',' AM'),'PM',' PM')
    

    will always return the date in HH:mm AM format.

    Hope that helps.

    PK

    0 讨论(0)
  • 2020-12-04 02:08

    You might be able to use:

    select
    
    convert(varchar,getdate(),114)
    

    You might be able to manually construct the query like:

    string query = string.Format("INSERT INTO test (DateOnlyField, TimeOnlyField) VALUES ('{0}', '1899-12-30 {1}')", DateTime.Today.ToShortDateString(), TimeString)
    

    I dunno if this might work to:

    Create Table Schedule( ScheduleID Integer Identity, ScheduledTime DateTime )
    
    Go
    
    Insert Into Schedule( ScheduledTime ) Values( '10:15:00 AM' )
    
    Go
    
    Select ScheduledTime As DBScheduledTime, Convert( VarChar( 10 ), ScheduledTime, 114 ) As ScheduledTime
    
    From Schedule
    
    Go
    
    Drop Table Schedule
    
    Go
    
    0 讨论(0)
  • 2020-12-04 02:19

    You can use the CONVERT function like this:

    SELECT CONVERT(varchar, your_datetime, 108)
    

    However, this is 24-hour clock, no AM/PM.

    0 讨论(0)
提交回复
热议问题