12 hr time format in sql like.. 02:32:00 PM - sql-server

How can I get the time like 02:32:00 PM in sql server?
I can get 24 hr with the following code.
CONVERT(VARCHAR(26), getdate(), 108)
But I want pure hh:mm:ss tt not with milliseconds.
I found the one with milliseconds.
select convert(varchar, getdate(), 109)
How to achieve that?

SELECT RIGHT('0' + LTRIM(STUFF(RIGHT(CONVERT(CHAR(26), CURRENT_TIMESTAMP, 109), 14),9, 4, ' ')),11)

See the SQL Server Books Online for a full listing of all supported styles / formats for date/time conversion using CONVERT.
There doesn't seem to be an exact match for what you're looking for, I'm afraid. You'll have to use some other, supported format and possibly do some string manipulation on the result yourself.
Those are all the supported formats - there is no way I'm aware of to extend this (other than writing a SQL CLR module yourself and plugging it into SQL Server).

Related

Convert UTC to EST in Query [MS SQL]

Long time reader first time poster :)
I am making a query that has a date formatted like this 2022-03-01T04:59:59.000+0000 since this is in UTC I need to get it into EST. I am having issues converting this. I have tried a few things I found online. The closest I have gotten is this.
SELECT CONVERT(datetime,
SWITCHOFFSET(CONVERT(datetimeoffset,
convert(varchar, [UTC Date Field], 1)),
DATENAME(TzOffset, SYSDATETIMEOFFSET())))
AS ColumnInLocalTime
from [Table Name] a (nolock)
But this is giving me an Conversion failed when converting date and/or time from character string. error. I am using MS SQL Server and I would consider my self competent in SQL. I know the data in the field I am using is stored as varchar. Any help would be appreciated.
Your value is not in a ISO8601 format that SQL Server recognizes, it's missing a : in the time zone part.
Let's just say you wouldn't have had this issue if your data would have been stored as datetimeoffset in the first place.
You can patch it up using STUFF, then just CONVERT with style 126
SELECT
SWITCHOFFSET(
CONVERT(datetimeoffset,
STUFF('2022-03-01T04:59:59.000+0000', 27, 0, ':'),
126),
DATENAME(TzOffset, SYSDATETIMEOFFSET())
)
db<>fiddle

How to format datetime in SQL SERVER

I am trying to port MySQL function DATE_FORMAT(date,'%y-%m-%d %h:%i:%s %p') to MsSQL equivalent by using CONVERT().
How to format equivalent datetime string in SQL SERVER 2012 to give this output '2014-05-24 01:24:37 AM'?
In SQL Server 2012 and up you can use FORMAT():
SELECT FORMAT(CURRENT_TIMESTAMP, 'yyyy-MM-dd hh:mm:ss tt')
In prior versions, you might need to concatenate two or more different datetime conversions to get what you need, for example:
SELECT
CONVERT(CHAR(10), CURRENT_TIMESTAMP, 23) + ' ' +
RIGHT('0' + LTRIM(RIGHT(CONVERT(CHAR(20), CURRENT_TIMESTAMP, 22), 11)), 11);
See the Date and Time Styles section of CAST and CONVERT (Transact-SQL) for all of the built-in formatting styles.
I would keep in mind that unless you have a good reason for it, I mean a really good reason, formatting is usually a better job for the technology displaying the data.

Search By Date in SQL Server 2012

We just upgraded to SQL Server 2012 from 2005. While I'm a novice, something this simple couldn't be this difficult. I used to be able to pull data from a table based on the date vs date and time. As it now stands I have:
Select * from receipts_table where receipt_cancel_date = '2013-09-20'
before we upgraded this would work fine. How can I run this and actually get the desired results as I know there's receipts with a cancel date of 2013-09-20.
Thanx
If you are passing string for a date parameter, best format is ISO (yyyymmdd) format. Otherwise even though your string work in some servers it might not work in another depending on the culture of the server. ISO format is culture independent.
Also remove the time part from receipt_cancel_date column by converting it to a DATE (if DATETIME) for comparison purpose.
Try this:
Select * from receipts_table
where convert(date, receipt_cancel_date) = convert(date,'20130920')
Or use 120 style with your format:
Select * from receipts_table
where convert(date, receipt_cancel_date) = convert(date,'2013-09-20',120)

what is the best way to insert only datepart of system date into SQL Server

I'm currently using
Convert(varchar, Getdate(), 101)
to insert only date part of system date into one of my sql server database tables.
my question is: is it the right way to do that or is there any other better method to do it?
I don't understand why you're converting the GETDATE() output (which is DATETIME already) to a VARCHAR and then SQL Server would convert it back to DATETIME upon inserting it again.
Just use:
INSERT INTO dbo.YourTable(SomeDateTimeColumn)
VALUES(GETDATE())
If you're doing that conversion to get rid of the time portion of the DATETIME, you should better:
use the DATE datatype (available in SQL Server 2008 and newer) to store only the DATE (no time)
if you're using SQL Server 2005 or earlier, use this conversion instead - should be much more efficient than two conversions!
INSERT INTO dbo.YourTable(SomeDateTimeColumn)
VALUES(DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
Update: did some performance testing, and in this particular case, it seems the amount of work that SQL Server needs to do is really the same - regardless of whether you're using the convert to varchar stripping the time and back to datetime approach that you already have, or whether you're using my get the number of days since date 0 approach. Doesn't seem to make a difference in the end.
The BEST solution however would still be: if you only need the date anyway - use a column of type DATE (in SQL Server 2008 and newer) and save yourself any conversions or manipulations of the GETDATE() output altogether.

Sql Server string to date conversion

I want to convert a string like this:
'10/15/2008 10:06:32 PM'
into the equivalent DATETIME value in Sql Server.
In Oracle, I would say this:
TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')
This question implies that I must parse the string into one of the standard formats, and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?
Try this
Cast('7/7/2011' as datetime)
and
Convert(DATETIME, '7/7/2011', 101)
See CAST and CONVERT (Transact-SQL) for more details.
Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:
Declare #d datetime
select #d = getdate()
select #d as OriginalDate,
convert(varchar,#d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select #d,convert(varchar,#d,101),101,'mm/dd/yy'
union all
select #d,convert(varchar,#d,102),102,'yy.mm.dd'
union all
select #d,convert(varchar,#d,103),103,'dd/mm/yy'
union all
select #d,convert(varchar,#d,104),104,'dd.mm.yy'
union all
select #d,convert(varchar,#d,105),105,'dd-mm-yy'
union all
select #d,convert(varchar,#d,106),106,'dd mon yy'
union all
select #d,convert(varchar,#d,107),107,'Mon dd, yy'
union all
select #d,convert(varchar,#d,108),108,'hh:mm:ss'
union all
select #d,convert(varchar,#d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select #d,convert(varchar,#d,110),110,'mm-dd-yy'
union all
select #d,convert(varchar,#d,111),111,'yy/mm/dd'
union all
select #d,convert(varchar,#d,12),12,'yymmdd'
union all
select #d,convert(varchar,#d,112),112,'yyyymmdd'
union all
select #d,convert(varchar,#d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select #d,convert(varchar,#d,114),114,'hh:mi:ss:mmm(24h)'
union all
select #d,convert(varchar,#d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select #d,convert(varchar,#d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select #d,convert(varchar,#d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'
In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.
DECLARE #d DATETIME = '2008-10-13 18:45:19';
-- returns Oct-13/2008 18:45:19:
SELECT FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss');
-- returns NULL if the conversion fails:
SELECT TRY_PARSE(FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
-- returns an error if the conversion fails:
SELECT PARSE(FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.
Until Denali, though, I think that #Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.
UPDATE for #dhergert:
SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');
SELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');
Results:
2008-10-15 22:06:32.000
2008-10-15 22:06:32.000
You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether 6/9/2012 is June 9th or September 6th.
SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.
By "arbitrarily", I mean "a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious." Frankly, I'm not sure there is any such algorithm.
Use this:
SELECT convert(datetime, '2018-10-25 20:44:11.500', 121) -- yyyy-mm-dd hh:mm:ss.mmm
And refer to the table in the official documentation for the conversion codes.
For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.
Short answer:
SELECT convert(date, '10/15/2011 00:00:00', 101) as [MM/dd/YYYY]
Other date formats can be found at SQL Server Helper > SQL Server Date Formats
Took me a minute to figure this out so here it is in case it might help someone:
In SQL Server 2012 and better you can use this function:
SELECT DATEFROMPARTS(2013, 8, 19);
Here's how I ended up extracting the parts of the date to put into this function:
select
DATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'
from MyTable
The most upvoted answer here are guravg's and Taptronic's. However, there's one contribution I'd like to make.
The specific format number they showed from 0 to 131 may vary depending on your use-case (see full number list here), the input number can be a nondeterministic one, which means that the expected result date isn't consistent from one SQL SERVER INSTANCE to another, avoid using the cast a string approach for the same reason.
Starting with SQL Server 2005 and its compatibility level of 90,
implicit date conversions became nondeterministic. Date conversions
became dependent on SET LANGUAGE and SET DATEFORMAT starting with
level 90.
Non deterministic values are 0-100, 106, 107, 109, 113, 130. which may result in errors.
The best option is to stick to a deterministic setting, my current preference are ISO formats (12, 112, 23, 126), as they seem to be the most standard for IT people use cases.
Convert(varchar(30), '210510', 12) -- yymmdd
Convert(varchar(30), '20210510', 112) -- yyyymmdd
Convert(varchar(30), '2021-05-10', 23) -- yyyy-mm-dd
Convert(varchar(30), '2021-05-10T17:01:33.777', 126) -- yyyy-mm-ddThh:mi:ss.mmm (no spaces)
This page has some references for all of the specified datetime conversions available to the CONVERT function. If your values don't fall into one of the acceptable patterns, then I think the best thing is to go the ParseExact route.
Personally if your dealing with arbitrary or totally off the wall formats, provided you know what they are ahead of time or are going to be then simply use regexp to pull the sections of the date you want and form a valid date/datetime component.
If you want SQL Server to try and figure it out, just use CAST
CAST('whatever' AS datetime)
However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years.
I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.
convert string to datetime in MSSQL implicitly
create table tmp
(
ENTRYDATETIME datetime
);
insert into tmp (ENTRYDATETIME) values (getdate());
insert into tmp (ENTRYDATETIME) values ('20190101'); --convert string 'yyyymmdd' to datetime
select * from tmp where ENTRYDATETIME > '20190925' --yyyymmdd
select * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS
You can easily achieve this by using this code.
SELECT Convert(datetime, Convert(varchar(30),'10/15/2008 10:06:32 PM',102),102)
This code solve my problem :
convert(date,YOUR_DATE,104)
If you are using timestamp you can you the below code :
convert(datetime,YOUR_DATE,104)
dateadd(day,0,'10/15/2008 10:06:32 PM')

Resources