How to get alone time 11:21 (highlighted in red) with SQL Server database? [duplicate] - sql

This question already has answers here:
SQL Server 2005 DateTime (return only hh:mm)
(2 answers)
Closed 6 years ago.
Done automatically add the date to the time of the database SQL Server 2005 Express. So when you add a new record in the database is added automatically date and time in the form of:
Create Table Baza_test
(
ID bigint IDENTITY (1,1) NOT NULL,
Client nvarchar (23)
address nvarchar (46)
DateOfAddmission datetime default CURRENT_TIMESTAMP
aaaaaadres nvarchar (46)
);
How to get alone time (highlighted in red):
with SQL Server database?

With the following query:
select CONVERT(VARCHAR(5), DateOfAddmission,108) AS [time] from Baza_test where ID = 1;

There is already similar question out there, please refer to the link bellow:
https://stackoverflow.com/a/7710495/4558361 by t-clausen.dk

The CONVERT(VARCHAR) answers are valid, if you want more flexibility and don't know the conversion codes like me :), you could do it with FORMAT:
DECLARE #d DATETIME = GETDATE();
SELECT FORMAT( #d, 'hh:mm') AS 'Time Result'

If 2012+
Select format(GetDate(),'HH:mm') --For the 24 clock
Select format(GetDate(),'hh:mm tt') --For the 12 clock
That said, I was informed that FORMAT() has a poor performance

Try like this,
12 HOURS FORMAT
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), DateOfAddmission, 100), 7)) FROM Baza_test
24 HOURS FORMAT
SELECT CONVERT(VARCHAR(5),DateOfAddmission, 108) FROM Baza_test

Apart from the answer given here another way is this -
SELECT CAST(CAST(GETDATE() AS Time(0)) AS VARCHAR(5))
Output
05:48
And in your case its -
SELECT CAST(CAST(DateOfAddmission AS Time(0)) AS VARCHAR(5)) AS [time]
FROM Baza_test
WHERE ID = 1;

Related

getdate() function [duplicate]

This question already has answers here:
How to return only the Date from a SQL Server DateTime datatype
(46 answers)
Closed 6 years ago.
How can I display only date while using getdate() function?
When I am using
select getdate() as Today's Date
It is giving me:
2016-05-18 08:32:07.100
But I only need:
2016-05-18
How to get this?
Use convert. The first argument truncates the length, and the last specifies the format you want the date in:
SELECT Convert(varchar(10), getdate(), 103) as [Today's Date]
If you are using SQL Server 2012+, you may also want to look at FORMAT - which in my opinion is a bit nicer to read/use.
Example: SELECT FORMAT(GETDATE(), 'dd/MM/yyyy')
See this msdn link for more info

How to cast GETDATE() to be only time ignore day,month and year [duplicate]

This question already has answers here:
Compare time part of DateTime data type in SQL Server 2005
(6 answers)
Closed 4 years ago.
I have a table for store takt-time. It's compound with "day_shift(1)" and "night_shift(0)" like below.
If I put current time(by using GETDATE() function ).
I need to know this current time is "day(1)" or "night(0)". my query like this.
SELECT [day_shift_flag]
FROM [company_working_time]
WHERE GETDATE() BETWEEN [start_time] AND[end_time]
But it can't found because a date received from GETDATE() isn't '1900-01-01'
How to compare a only time and ignore day,month,year.
What should I do?
You can cast a DateTime as a Time data type. For example:
SELECT
[day_shift_flag]
FROM [company_working_time]
WHERE
CAST(GETDATE() AS TIME) BETWEEN CAST([start_time] AS TIME) AND CAST([end_time] AS TIME)
By Following Way You can Ignore the day,month,year
SELECT [day_shift_flag]
FROM [company_working_time]
WHERE DatePart(HH,GETDATE()) BETWEEN DatePart(HH,[start_time]) AND DatePart(HH,[end_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' );

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' );

Simple DateTime sql query

How do I query DateTime database field within a certain range?
I am using SQL SERVER 2005
Error code below
SELECT *
FROM TABLENAME
WHERE DateTime >= 12/04/2011 12:00:00 AM
AND DateTime <= 25/05/2011 3:53:04 AM
Note that I need to get rows within a certain time range. Example, 10 mins time range.
Currently SQL return with Incorrect syntax near '12'."
You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'
You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:
SELECT *
FROM TABLENAME
WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'
See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:
Sql Server string to date conversion
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
You can execute below code
SELECT Time FROM [TableName] where DATEPART(YYYY,[Time])='2018' and DATEPART(MM,[Time])='06' and DATEPART(DD,[Time])='14
SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.
select getdate()
O/P
----
2011-05-25 17:29:44.763
select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'
O/P
---
22/06/1432 5:29:44:763PM
Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :
Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.
Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).
if you have a type of datetime and you want to check between dates only ,,,use cast to select between two dates ....
example...
... where cast( Datetime as date) >= cast( Datetime as date) AND cast( Datetime as date) <= cast( Datetime as date)