How to convert GetDate() to "YYYY-MM-DD-HHMM" format? - sql-server

I've been looking for the answer and could not find the exact one satisfying my needs.
I'm looking for the way to convert Datetime value into YYYY-MM-DD-HHMM format.
I tried that one:
select CONVERT(varchar(20),GETDATE(), 120) + replace(convert(varchar(5),getdate(),108),':','')
But it did not give me the right results
Is there any practical way to do it?

In SQL Server 2012 or later you can use the built-in Format() function for this:
Select Format(GetDate(), N'yyyy-MM-dd-HHmm')

This works for me:
select CONVERT(varchar(10),GETDATE(), 20) + '-' + replace(convert(varchar(5),getdate(),108),':','')
I'm not sure if this is efficient or not, though

Related

How to convert Oracle TO_NUMBER to SQL Server

I am migrating some SQL scripts from Oracle to SQL Server and have come across an issue when trying to convert Oracles TO_NUMBER into T-SQL code. Looked through the web for some time but never found the answer but they all say to convert hex using CAST or CONVERT with VARBINARY.
An example of the issue I am getting is below.
In Oracle:
select
to_number( '000000000000000000001111', 'XXXXXXXXXXXXXXXXXXXXXXXX' )
from
dual
returns 4369
When trying to use T-SQL CONVERT:
select
CONVERT(VARBINARY, '000000000000000000001111')
returns 0x303030303030303030303030303030303030303031313131
and
select
CONVERT(INT, CONVERT(VARBINARY, '000000000000000000001111'))
returns 825307441
Any help would be greatly appreciated.
Thanks
TSQL has binary literals, so you can write it like this:
select CONVERT(INT, 0x000000000000000000001111)
outputs
4369
If you are starting with a hex string, you can use convert with the binary style of 1, or 2, so
select convert(int, convert(varbinary(1024),'000000000000000000001111', 2))
outputs
4369
This should do the work.
select convert(bigint, convert(Varbinary(MAX), '000000000000000000001111',2))

Alternative to using FORMAT in SQL Server 2008 R2

I created a SELECT using the following in SQL Server 2012:
SELECT
CAST(FORMAT(CONVERT(DATETIME, date_time, 127), 'yyyy-MM-ddTHH:mm:ssZ') AS NVARCHAR(20)) TimeStamp,
FROM myTable
This will result in a date formatted like 2019-03-15T13:25:19Z
How can I achieve the same result using SQL Server 2008 R2 or older?
You can achieve this far more easily by just using CONVERT:
SELECT CONVERT(varchar(19),GETDATE(),127) + 'Z';
As I mentioned in my comment FORMAT is actually an awful function, it performs terribly. I posted an answer to another question earlier today on just how badly it does compared to a CONVERT. Don't just use this expression on your 2008- servers, replace the FORMAT expression on your 2012+ servers with this one too.
I think this does what you want:
select replace(convert(varchar(255), getdate(), 120), ' ', 'T') + 'Z'
Code 127 returns milliseconds, which you do not seem to want, so 120 seems more appropriate.

Convert DDMMYYYY to YYYYMMDD date format in sql server?

I have a date in table as "26052016" in format DDMMYYYY
I want to convert this date to "YYYYMMDD" format.
Any idea
I have tried this method
select CONVERT(varchar(8),[doc-date],112) FROM C034_PDK_ParallelBillingSourceExtract
But this is gives me the same date as a result.
Please help me
I can find this way, i don't know if any other way exist or not..
declare #date nvarchar(max)='01052016'
select convert(varchar(8),cast(CONCAT(SUBSTRING(#date,3,2),'/',SUBSTRING(#date,1,2),'/',SUBSTRING(#date,5,4)) as date),112)as [YYYYMMDD]
Clear Code:
declare #date nvarchar(max)='01052016'
declare #date1 date
set #date1 =cast(CONCAT(SUBSTRING(#date,3,2),'/',SUBSTRING(#date,1,2),'/',SUBSTRING(#date,5,4)) as date)
select convert(varchar(8),#date1,112)as [YYYYMMDD]
If you are using Sql version< 2012 then you need to skip CONCAT and use + for string concatination.
SELECT CONVERT(VARCHAR(8), doc-date, 112) AS [YYYYMMDD] from
C034_PDK_ParallelBillingSourceExtract
Check ... this should work correctly.
Thanks
SELECT CONVERT(VARCHAR(8), '26052016', 112) AS [YYYYMMDD] from
C034_PDK_ParallelBillingSourceExtract
Try like this,
SELECT substring([doc-date], 5, 4) + substring([doc-date], 3, 2) + substring([doc-date], 1, 2) AS [YYYYMMDD]
FROM C034_PDK_ParallelBillingSourceExtract
There are differet ways to do it.
The best way is to use substring method as you know the character positions are going to remain same.
For Example
Suppose your date is - 31122015
Pick the portions of date using substring method and concatenate them
select SUBSTRING('31122015',5,4) + SUBSTRING('31122015',3,2) + SUBSTRING('31122015',1,2)
The result would be - 20153112
Since SQL Server 2016 we have a couple of handy tools for this:
Use DATEFROMPARTS and SUBSTRING to convert odd date formats from any arrangement within a Varchar to an actual date:
SELECT DATEFROMPARTS(SUBSTRING('31122015',5,4), SUBSTRING('31122015',3,2), SUBSTRING('31122015',1,2))
Use FORMAT to Convert an actual date to YYYYMMDD:
SELECT FORMAT(MyDate, 'yyyyMMdd')
watch out for the yyyyMMdd, that's the only part of MS SQL that is case-sensitive. Lower case mm is "minutes" and upper case MM is "Month", upper case YYYY or DD is nothing, and will just add letters to your output!

Remove time from DateTime sql server 2005

I need date part from datetime. in format of "dd-mm-yyyy"
I have tried follwoing
Query:
select Convert(varchar(11), getdate(),101)
Output:
01/11/2011
Query
SELECT cast(floor(cast(GETDATE() as float)) as datetime)
Output
2011-01-11 00:00:00.000
Query:
SELECT
CONVERT(VARCHAR(MAX),DATENAME(DD,GETDATE())) + '-' +
CONVERT(VARCHAR(MAX),DATEPART(MONTH,GETDATE())) + '-' +
CONVERT(VARCHAR(MAX),DATENAME(YYYY,GETDATE())) `
Output:
11-1-2011 i.e. "d-m-yyyy"
I required output in "dd-mm-yyyy" format.
SELECT CONVERT(VARCHAR(10),GETDATE(),105)
Try:
SELECT convert(varchar, getdate(), 105)
More here.
Here you can find some examples how to do this: http://blog.pengoworks.com/index.cfm/2009/1/9/Useful-tips-and-tricks-for-dealing-with-datetime-in-SQL
Using the CONVERT function "works" but only if you're comparing strings with strings. To compare dates effectively, you really need to keep the SMALLDATETIME data type strongly typed on both side of the equation (ie "="). Therefore 'apros' comment above is really the best answer here because the blog mentioned has the right formulas to use to strip off the time component by "flattening" it to midnight (ie 12:00:00) via rounding and any date column in SQL Server 2005 will always default to 12:00:00 if the date is given without a time.
This worked for me ...
select dateadd(day, datediff(day, '20000101', #date), '20000101')

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