How to Convert 'YYYY-MM-DD-HH.MM.SS.MI' to 'YYYY-MM-DD' in SQL Server from DB2 - sql-server

From DB2, we are getting one column value "2018-01-12-13.28.37.111972" like this format("YYYY-MM-DD-HH.MM.SS.MI"). I want to convert this one to "YYYY-MM-DD" in sql server. I used Cast(fieldname as date) is not working.

If you are interested in both the date and time, Larnu's answer is the way to go.
If it's only the date you care about, you can simply use left to get only the date part of the string:
SELECT CAST(LEFT('2018-01-12-13.28.37.111972', 10) As Date)
BTW, datetime isn't stored with a display format.

I can't speak for DB2, but I suspect you're it's passing the value as a varchar, and not a datetime, and hence the problem. If DB2 has to pass the values as a varchar, you have use STUFF to fix the values:
SELECT DB2.DateString,
CONVERT(datetime2(6),STUFF(STUFF(STUFF(DB2.DateString,11,1,'T'),14,1,':'),17,1,':'))
FROM (VALUES('2018-01-12-13.28.37.111972'))DB2(DateString);

select convert(varchar(10), '2018-01-12-13.28.37.111972', 5)
will produce: 2018-01-12

With a few string functions you can transform the timestamp text to a format that can be casted to a DATE or a DATETIME
For example this snippet:
select db2col,
try_cast(left(db2col, 10)+' '+replace(substring(db2col,12,8),'.',':')+substring(db2col,20,4) as datetime) as col_as_datetime,
cast(left(db2col, 10) as date) as col_as_date
from (values
('2018-01-12-13.28.37.111972'),
('2018-02-15-14.29.54.123456')
) as vals(db2col)
Returns:
db2col col_as_datetime col_as_date
-------------------------- ----------------------- ----------
2018-01-12-13.28.37.111972 2018-01-12 13:28:37.110 2018-01-12
2018-02-15-14.29.54.123456 2018-02-15 14:29:54.123 2018-02-15

Related

Ms sql output in date format

I have a requirement. I have datetime field and I want data in datatype=date
Existing date: 2019-11-13 00: 00: 00: 000 ; datatype=datetime
Expected output require: 11/13/2019 (mm/dd/yyyy) ;
datatype= date
Please help me.
If the core requirement is a right type then:
SET DATEFORMAT MDY;
SELECT CAST(GETDATE() as DATE);
Explicit DATEFORMAT added becaise the output depends on a language settings, so can be yyyy/mm/dd or mm/dd/yyyy, some apps can be sensitive to this, as example SSRS.
However, if there is still a requirement to get value in a precisely right format on a database side, then consider to use a FORMAT statement:
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy')
I have datetime field and I want data in datatype=date
If you want the data type as DATE, in that case you can try like following.
SELECT CAST(YourDateTimeColumn AS DATE) from [YourTable]
Formatting part you should be doing in UI.
You can use CONVERT() :
SELECT t.datecol, CONVERT(VARCHAR(10), t.datecol, 101)
FROM table t;
Your desired date format requires varchar type, if you want date only then you can do instead :
SELECT t.datecol, CONVERT(DATE, t.datecol)
FROM table t;
If you don't want to convert the type, then these type of conversation should do in presentation layer instead.

Convert One Datetime format to another in SQL Server

I have a datetime2 format in my Database 2015-06-22 06:23:42.790. I need to convert this into the following format 22/06/2015 06:23:42.790.
Is it possible?
Here is one way to do this:
DECLARE #date DATETIME2 = '2015-06-22 06:23:42.790';
SELECT cast(convert(VARCHAR(10), cast(LEFT(#date, 10) AS DATE), 3) AS VARCHAR(10))
+ ' ' + substring(cast(#date AS VARCHAR(50)), 12, 12)
Query breakdown:
First part: take first 10 characters from your datefield and then convert it to date style 3 (dd/mm/yyyy).
Second part: Add a space between date and time.
Third part: cast your datefield as varchar and extract the time which should always start in the 12th position of your string.
Join them all together and there you have it! Hope this helps!
Don't try to convert the database layout. Year Month Day is how SQL server shows the date because it ignores any international date formats.
I notice you want it as 22/06/2015 are you in the UK ? In the USA it would be 06/22/2015 Not such a problem because it's obvious that the 22 is the day. But if the date was 05/06/2015 how would sql or anyone know what day or month you're talking about.
So, get in to the habit of working in the ISO format year month day.
You don't mention what programming language. When reading data out of the database youd read it into a datetime variable. That will convert the date correctly into whatever locale your user is using. Different languages have different ways of getting the date into a datettime variable.
If it's only for display-use you can convert to varchar with FORMAT() function:
DECLARE #tab TABLE
(
datevalue DATETIME2
)
INSERT INTO #tab VALUES(GETDATE())
SELECT datevalue,
FORMAT(datevalue,'dd/MM/yyyy hh:mm:ss.fff') as newformat
FROM #tab

SQL Server function to return minimum date (January 1, 1753)

I am looking for a SQL Server function to return the minimum value for datetime, namely January 1, 1753. I'd rather not hardcode that date value into my script.
Does anything like that exist? (For comparison, in C#, I could just do DateTime.MinValue)
Or would I have to write this myself?
I am using Microsoft SQL Server 2008 Express.
You could write a User Defined Function that returns the min date value like this:
select cast(-53690 as datetime)
Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.
Alternately, you could use this query if you prefer it for better readability:
select cast('1753-1-1' as datetime)
Example Function
create function dbo.DateTimeMinValue()
returns datetime as
begin
return (select cast(-53690 as datetime))
end
Usage
select dbo.DateTimeMinValue() as DateTimeMinValue
DateTimeMinValue
-----------------------
1753-01-01 00:00:00.000
Have you seen the SqlDateTime object? use SqlDateTime.MinValue to get your minimum date (Jan 1 1753).
As I can not comment on the accepted answer due to insufficeint reputation points my comment comes as a reply.
using the select cast('1753-1-1' as datetime) is due to fail if run on a database with regional settings not accepting a datestring of YYYY-MM-DD format.
Instead use the select cast(-53690 as datetime) or a Convert with specified datetime format.
Enter the date as a native value 'yyyymmdd' to avoid regional issues:
select cast('17530101' as datetime)
Yes, it would be great if TSQL had MinDate() = '00010101', but no such luck.
Here is a fast and highly readable way to get the min date value
Note: This is a Deterministic Function, so to improve performance further we might as well apply WITH SCHEMABINDING to the return value.
Create a function
CREATE FUNCTION MinDate()
RETURNS DATETIME WITH SCHEMABINDING
AS
BEGIN
RETURN CONVERT(DATETIME, -53690)
END
Call the function
dbo.MinDate()
Example 1
PRINT dbo.MinDate()
Example 2
PRINT 'The minimimum date allowed in an SQL database is ' + CONVERT(VARCHAR(MAX), dbo.MinDate())
Example 3
SELECT * FROM Table WHERE DateValue > dbo.MinDate()
Example 4
SELECT dbo.MinDate() AS MinDate
Example 5
DECLARE #MinDate AS DATETIME = dbo.MinDate()
SELECT #MinDate AS MinDate
It's not January 1, 1753 but select cast('' as datetime) wich reveals: 1900-01-01 00:00:00.000 gives the default value by SQL server.
(Looks more uninitialized to me anyway)
This is what I use to get the minimum date in SQL Server. Please note that it is globalisation friendly:
CREATE FUNCTION [dbo].[DateTimeMinValue]()
RETURNS datetime
AS
BEGIN
RETURN (SELECT
CAST('17530101' AS datetime))
END
Call using:
SELECT [dbo].[DateTimeMinValue]()
What about the following?
declare #dateTimeMin as DATETIME = datefromparts(1753, 1, 1);
select #dateTimeMin;
The range for datetime will not change, as that would break backward compatibility. So you can hard code it.

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

sql convert date format not working

I can not convert field run_date on sysjobhistory table from yyyymmdd to mmddyyyy.
select CONVERT(varchar(10),run_date),101) as Date from sysjobhistory
Please correct me. Thanks.
declare #dt date ='20161025'
select #dt,CONVERT(varchar(15),#dt,101)
See here
Date type does not have yyyymmdd nor mmddyyyy. This type only valid for string (as varchar, nvarchar). Plus, you have extra ) after rundate.
The correct one should be:
select CONVERT(varchar(10),run_date,101) from sysjobhistory
where 101 is style argument: https://msdn.microsoft.com/en-us/library/ms187928.aspx
shouldn't it be: CONVERT (varchar(10), run_date, 101). What I am trying to say is that you have an extra parenthesis after run_date.

Resources