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
If you are using MySql
you can use TIME_FORMAT()
Code ↓↓
SELECT name, time_format(datatime,'%H:%i') as tine from cuatomer
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 )
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.
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
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
You can use the CONVERT function like this:
SELECT CONVERT(varchar, your_datetime, 108)
However, this is 24-hour clock, no AM/PM.