Get Time from Getdate() - sql

I would like to take the Getdate() results of,
for example
2011-10-05 11:26:55.000
into
11:26:55 AM
I have looked other places and found
Select RIGHT(CONVERT(VARCHAR, GETDATE(), 100),7)
which gives me
11:26AM
It's so close I can taste it!

select convert(varchar(10), GETDATE(), 108)
returned 17:36:56 when I ran it a few moments ago.

You might want to check out this old thread.
If you can omit AM/PM portion and using SQL Server 2008, you should go with the approach suggested here
To get the rid from nenoseconds in time(SQL Server 2008), do as below :
SELECT CONVERT(TIME(0),GETDATE()) AS HourMinuteSecond
I hope it helps!!

Did you try to make a cast from date to time?
select cast(getdate() as time)
Reviewing the question, I saw the 'AM/PM' at end. So, my answer for this question is:
select format(getdate(), 'hh:mm:ss tt')
Run on Microsoft SQL Server 2012 and Later.

To get the format you want:
SELECT (substring(CONVERT(VARCHAR,GETDATE(),22),10,8) + ' ' +
SUBSTRING(CONVERT(VARCHAR,getdate(),22), 19,2))
Why are you pulling this from sql?

Let's try this
select convert(varchar, getdate(), 108)
Just try a few moment ago

If it's SQL Server 2005 there is no TIME datatype. The easiest way to get only the time component is to set the date to 1/1/1900.
DECLARE #time DATETIME
SET #Time = GETDATE()
SELECT DATEADD(dd,DATEDIFF(dd,#time,'1/1/1900'),#time)

You will be able to get the time using below query:
select left((convert(time(0), GETDATE ())),5)

You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:
declare #fromtime time = '09:30'
declare #totime time
SET #totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if #fromtime <= #totime
begin print 'true' end
else begin print 'no' end

Related

Date conversion doesn't work in where clause

I am trying to query against the columns SOE (datetime field) and Answer (varchar field) from a table where NOT ALL Answer values are dates but some of them are. If I remove the datediff from the 'where' clause, I'm able to run the query just fine. But on including it, it errors out saying that 'Conversion failed when converting date and/or time from character string'.
For context, I'm using SQL Server 2014.
This is what my query looks like:
select ID,
convert(datetime, Answer, 121) as Answer,
datediff(dd,convert(datetime,
Answer, 121), SOE) as Days
from table
where Type in (1) and SOE between '2019-01-01' and '2019-03-31'
and FormLocation = 'M1005_INP_DISCHARGE_DT'
and PayorType = 'Medicare'
and Answer <> ' '
datediff(dd, convert(datetime, Answer, 121), SOE) <= 5
Any tips on how to resolve this would be appreciated.
Before doing the conversion to datetime make sure the data in the "Answer" field can be converted to date. Try this...
and ((isdate(Answer) = 1) and (datediff(dd, convert(datetime, Answer, 121), SOE) <= 5))
Since 2012 you can use try_convert().
...
datediff(dd, try_convert(datetime, Answer, 121), SOE) <= 5
...
try_convert() returns NULL if the conversion doesn't succeed. And so does datediff() then. So you might want to handle that case some way.
Using apply you can save yourself some repetitive code:
select ID,
answer_datetime as Answer,
datediff(day, answer_datetime, SOE) as Days
from table t cross apply
(values (try_convert(datetime, Answer, 121))) v(answer_datetime)
where Type in (1) and
SOE between '2019-01-01' and '2019-03-31' and
FormLocation = 'M1005_INP_DISCHARGE_DT' and
PayorType = 'Medicare' and
Answer <> ' ' and
datediff(day, answer_datetime, SOE) <= 5;
But you should really fix the data definitions so date/times are stored using the correct type.

Convert to HH:MM in SQL Server

I would like to convert a date time format to hh:mm using SQL Server.
For example: convert this value 2017-08-17 15:31:18.217 into 15:31.
If anyone knows how to do this, please help.
Here is one way to do it:
DECLARE #DateTime datetime = '2017-08-17 15:31:18.217'
SELECT CONVERT(char(5), #DateTime, 108)
Result: 15:31
SELECT FORMAT(cast('2017-08-17 15:31:18.217' as datetime),'hh:mm')
SELECT CONVERT(VARCHAR(5), GETDATE(), 108)
You may want to use TRY_CONVERT if supported,and you don't always have a in that column.
One thing, the value that gets converted needs to be of type DATETIME.
Please execute these 2 queries , you will get the hours and minutes of current time.
SELECT GETDATE()
SELECT CONVERT(VARCHAR(5), CAST(GETDATE() AS TIME))

SQLServer remove Date part of datetime [duplicate]

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 the date is
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
In SQL Server if you need only the hh:mi, you can use:
DECLARE #datetime datetime
SELECT #datetime = GETDATE()
SELECT RIGHT('0'+CAST(DATEPART(hour, #datetime) as varchar(2)),2) + ':' +
RIGHT('0'+CAST(DATEPART(minute, #datetime)as varchar(2)),2)
If you want only the hour of your datetime, then you can use DATEPART() - SQL Server:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select datepart(hour, #dt) -- returns 8
In SQL Server 2008+ you can CAST() as time:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select CAST(#dt as time) -- returns 08:25:53
I know this is an old question, but since the other answers all
return strings (rather than datetimes),
rely on the internal representation of dates (conversion to float, int, and back) or
require SQL Server 2008 or beyond,
I thought I'd add a "pure" option which only requires datetime operations and works with SQL Server 2005+:
SELECT DATEADD(dd, -DATEDIFF(dd, 0, mydatetime), mydatetime)
This calculates the difference (in whole days) between date zero (1900-01-01) and the given date and then subtracts that number of days from the given date, thereby setting its date component to zero.
Try this in SQL Server 2008:
select *
from some_table t
where convert(time,t.some_datetime_column) = '5pm'
If you want take a random datetime value and adjust it so the time component is 5pm, then in SQL Server 2008 there are a number of ways. First you need start-of-day (e.g., 2011-09-30 00:00:00.000).
One technique that works for all versions of Microsoft SQL Server as well as all versions of Sybase is to use convert/3 to convert the datetime value to a varchar that lacks a time component and then back into a datetime value:
select convert(datetime,convert(varchar,current_timestamp,112),112)
The above gives you start-of-day for the current day.
In SQL Server 2008, though, you can say something like this:
select start_of_day = t.some_datetime_column
- convert(time, t.some_datetime_column ) ,
from some_table t
which is likely faster.
Once you have start-of-day, getting to 5pm is easy. Just add 17 hours to your start-of-day value:
select five_pm = dateadd(hour,17, t.some_datetime_column
- convert(time,t.some_datetime_column)
)
from some_table t
Note that from MS SQL 2012 onwards you can use FORMAT(value,'format')
e.g. WHERE FORMAT(YourDatetime,'HH:mm') = '17:00'
"For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."
So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:
SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'
This should strip away the date part:
select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()
and return a datetime with a default date of 1900-01-01.
you can use CONVERT(TIME,GETDATE()) in this case:
INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))
or if you want print it or return that time use like this:
DECLARE #dt TIME
SET #dt = CONVERT(TIME,GETDATE())
PRINT #dt
select cast(getdate() as time(0))
returns for example :- 15:19:43
replace getdate() with the date time you want to extract just time from!
SELECT DISTINCT
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108)
FROM
CONSOLIDATED_LIST AS A
WHERE
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108) BETWEEN '15:00:00' AND '15:45:00'
declare #datetime as datetime
set #datetime = getdate()
select cast(cast(#datetime as time) as varchar(8))
For year:
SELECT DATEPART(YEAR, '2021-03-21' );
For hour:
SELECT DATEPART(HOUR, '2021-03-21 08:50:30' );

How to display the date as mm/dd/yyyy hh:mm Am/PM using sql server 2008 r2?

My sample query is
SELECT D30.SPGD30_LAST_TOUCH_Y
from CSPGD30_TRACKING D30
My given date format is like "2013-01-01 00:00:00.000". I need to convert this date format to "mm/dd/yyyy hh:mm AM/PM". Do you have any idea about that?
I think there is no single format to give them both. Try this using Convert; Sql-Demo
declare #mydate datetime = getdate()
select convert(varchar(10),#mydate, 101) + right(convert(varchar(32),#mydate,100),8)
| COLUMN_0 |
----------------------
| 02/22/2013 9:36AM |
The FORMAT() function is available from version 2012 onwards.
Once upgraded, you can use
select FORMAT(#date,'MM/dd/yyyy hh:mm:s tt')
Use this
select CONVERT(VARCHAR(10), mydate, 101) + ' ' + RIGHT(CONVERT(VARCHAR, mydate, 100), 7) from tablename
Try this
SELECT convert(varchar(20), GetDate(), 0);
To extract only AM/PM
substring(convert(varchar(30), GetDate(), 9), 25, 2);
Fiddle
Use the following scenario for getting date,time,day,month,year,hours,minutes,seconds,AM/PM
:)
SELECT UpdatedOn ,
CONVERT(varchar,UpdatedOn,100) DateTime,
CONVERT(varchar,UpdatedOn,10) Date ,
CONVERT(varchar,UpdatedOn,108) Time ,
substring(CONVERT(varchar,UpdatedOn,106),1,2) Day,
substring(CONVERT(varchar,UpdatedOn,106),4,3) CMonth,
substring(CONVERT(varchar,UpdatedOn,105),4,2) NMonth,
substring(CONVERT(varchar,UpdatedOn,106),8,4) Year,
left(right(CONVERT(varchar,UpdatedOn,100),7),2) Hours_12,
substring(CONVERT(varchar,UpdatedOn,108),1,2) Hours_24,
substring(CONVERT(varchar,UpdatedOn,108),4,2) Minutes,
substring(CONVERT(varchar,UpdatedOn,108),7,2) Second,
right(CONVERT(varchar,UpdatedOn,100),2) AM_PM
FROM dbo.DeviceAssignSim
WHERE AssignSimId=55;
You can do it like this:
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]
For more information look this:
date-format
Use the convert method to format a datetime value. Example:
select convert(varchar(20), D30.SPGD30_LAST_TOUCH_Y, 101)
The third parameter determines the format. You can find the available formats in the cast and convert documentation.
Use this
Select (Convert(Varchar,GetDate(),101))+' '+(Right(('0'+(LTrim((Left((Right((Convert(Varchar,GetDate(),100)),7)),5))))),5))+' '+(Right((Convert(Varchar,GetDate(),100)),2))
I realize this is a 8 year old question but it was answered in many ways and none are simple enough. This is what I found to be simple and matches just about what the user is asking for (year is two digits, and seconds are present), assuming that the date he is getting is from GETDATE(), not that it matters but that is where my answer comes from.
SELECT CONVERT(varchar, D30.SPGD30_LAST_TOUCH_Y, 22) AS [DateTime]
12/16/20 10:19:18 AM

Time part of a DateTime Field in SQL

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 the date is
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
In SQL Server if you need only the hh:mi, you can use:
DECLARE #datetime datetime
SELECT #datetime = GETDATE()
SELECT RIGHT('0'+CAST(DATEPART(hour, #datetime) as varchar(2)),2) + ':' +
RIGHT('0'+CAST(DATEPART(minute, #datetime)as varchar(2)),2)
If you want only the hour of your datetime, then you can use DATEPART() - SQL Server:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select datepart(hour, #dt) -- returns 8
In SQL Server 2008+ you can CAST() as time:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select CAST(#dt as time) -- returns 08:25:53
I know this is an old question, but since the other answers all
return strings (rather than datetimes),
rely on the internal representation of dates (conversion to float, int, and back) or
require SQL Server 2008 or beyond,
I thought I'd add a "pure" option which only requires datetime operations and works with SQL Server 2005+:
SELECT DATEADD(dd, -DATEDIFF(dd, 0, mydatetime), mydatetime)
This calculates the difference (in whole days) between date zero (1900-01-01) and the given date and then subtracts that number of days from the given date, thereby setting its date component to zero.
Try this in SQL Server 2008:
select *
from some_table t
where convert(time,t.some_datetime_column) = '5pm'
If you want take a random datetime value and adjust it so the time component is 5pm, then in SQL Server 2008 there are a number of ways. First you need start-of-day (e.g., 2011-09-30 00:00:00.000).
One technique that works for all versions of Microsoft SQL Server as well as all versions of Sybase is to use convert/3 to convert the datetime value to a varchar that lacks a time component and then back into a datetime value:
select convert(datetime,convert(varchar,current_timestamp,112),112)
The above gives you start-of-day for the current day.
In SQL Server 2008, though, you can say something like this:
select start_of_day = t.some_datetime_column
- convert(time, t.some_datetime_column ) ,
from some_table t
which is likely faster.
Once you have start-of-day, getting to 5pm is easy. Just add 17 hours to your start-of-day value:
select five_pm = dateadd(hour,17, t.some_datetime_column
- convert(time,t.some_datetime_column)
)
from some_table t
Note that from MS SQL 2012 onwards you can use FORMAT(value,'format')
e.g. WHERE FORMAT(YourDatetime,'HH:mm') = '17:00'
"For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."
So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:
SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'
This should strip away the date part:
select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()
and return a datetime with a default date of 1900-01-01.
you can use CONVERT(TIME,GETDATE()) in this case:
INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))
or if you want print it or return that time use like this:
DECLARE #dt TIME
SET #dt = CONVERT(TIME,GETDATE())
PRINT #dt
select cast(getdate() as time(0))
returns for example :- 15:19:43
replace getdate() with the date time you want to extract just time from!
SELECT DISTINCT
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108)
FROM
CONSOLIDATED_LIST AS A
WHERE
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108) BETWEEN '15:00:00' AND '15:45:00'
declare #datetime as datetime
set #datetime = getdate()
select cast(cast(#datetime as time) as varchar(8))
For year:
SELECT DATEPART(YEAR, '2021-03-21' );
For hour:
SELECT DATEPART(HOUR, '2021-03-21 08:50:30' );