I have requirement to convert multiple date types input entered by users to standard date format i.e
Input Date Format from old table is of Varchar data type and can be either of DD/MM/YYYY or DDMMYYYY or DDMMYY formats (manually entered by users)
Example: 08/10/2013 or 08102013 or 081013
And my requirement is to convert this to standard date format, how can I achieve this ?
Any help would be appreciated
SQL Fiddle
MS SQL Server 2008 Schema Setup:
create table YourTable(DateCol varchar(20))
insert into YourTable values ('08/10/2013'), ('08102013'), ('081013')
Query 1:
select
case len(DateCol)
when 10 then convert(date, DateCol, 103)
when 8 then convert(date, stuff(stuff(DateCol, 5, 0, '/'), 3, 0, '/'), 103)
when 6 then convert(date, stuff(stuff(DateCol, 5, 0, '/'), 3, 0, '/'), 3)
end
from YourTable
Results:
| COLUMN_0 |
|------------|
| 2013-10-08 |
| 2013-10-08 |
| 2013-10-08 |
Related
I'm looking to convert a users input that will be a NVARCHAR to a UK date
The user's input will always be a maximum of 6 digits.
For example:
151119 (DDMMYY) --> 15NOV19
120119 (DDMMYY) --> 12JAN19
You need a valid DATE or DATETIME / DATETIME2 value first. You can get this value using this SELECT query with CONVERT:
SELECT CONVERT(DATE,
SUBSTRING('151119', 3, 2) + '-'
+ SUBSTRING('151119', 1, 2) + '-'
+ SUBSTRING('151119', 5, 2)
, 10);
Now you have two possibilities to get the date in the expected format (DDMMMYY).
1 - solution using DATENAME:
-- set the date value (from custom date value).
DECLARE #dDateValue AS DATE = CONVERT(DATE,
SUBSTRING('150419', 3, 2) + '-'
+ SUBSTRING('150419', 1, 2) + '-'
+ SUBSTRING('150419', 5, 2)
, 10);
-- format the date value to the expected format.
SELECT DATENAME(DD, #dDateValue) +
UPPER(LEFT(DATENAME(MM, #dDateValue), 3)) +
RIGHT(DATENAME(YY, #dDateValue), 2);
2 - solution using CONVERT:
-- set the date value (from custom date value).
DECLARE #dDateValue AS DATE = CONVERT(DATE,
SUBSTRING('150419', 3, 2) + '-'
+ SUBSTRING('150419', 1, 2) + '-'
+ SUBSTRING('150419', 5, 2)
, 10);
-- format the date value to the expected format.
SELECT UPPER(REPLACE(CONVERT(VARCHAR, #dDateValue, 6), ' ', ''));
demo on dbfiddle.uk
Note: I recommend to store the date values on columns with DATE or DATETIME data type. You can format the date value on your application or using format functions on SQL-Server directly.
You need to alter the string into something that looks even little like a normal date format, then you can use convert:
declare #textDate nvarchar(6) = '120119';
select #textDate
, stuff(stuff(#textDate, 3,0,'/'), 6,0,'/')
, convert(date, stuff(stuff(#textDate, 3,0,'/'), 6,0,'/'), 3);
Gives:120119,12/01/19,2019-01-12
As that last one is a valid date datatype, you can now use Format().
Though obviously 2 digit years are a bad idea in the first place.
Forgot to say, the 3 is for UK 2 digit format(dd/mm/yy), and you can see the other choices here.
I highly recommend to work with date values on columns AS DATE or DATETIME type. This is a simple implementation for your need :
SQL Fiddle
MS SQL Server 2017 Schema Setup:
create table test (mydate nvarchar(6))
insert into test (mydate)values('151119')
insert into test (mydate)values('120119')
Query 1:
select FORMAT(CONVERT(DATE, dates), 'dd/MM/yyyy ') from (select left(mydate,2)
+
CASE SUBSTRING(mydate, 3, 2)
WHEN '01' THEN 'JAN'
WHEN '02' THEN 'FEB'
WHEN '03' THEN 'MAR'
WHEN '04' THEN 'APR'
WHEN '05' THEN 'MAY'
WHEN '06' THEN 'JUN'
WHEN '07' THEN 'JUL'
WHEN '08' THEN 'AUG'
WHEN '09' THEN 'SEP'
WHEN '10' THEN 'OCT'
WHEN '11' THEN 'NOV'
WHEN '12' THEN 'DEC'
ELSE 'error'
END
+ right(mydate,2) AS 'dates'
from test ) AS T
Results:
| |
|-------------|
| 15/11/2019 |
| 12/01/2019 |
I want the count of number of days from 25/02/2019 in month of February and expected result is 4
I tried using master..spt_values in sql server but did not get expected result
declare #fdays int ,#d date=cast('20190201' as date),#JoinDate date=cast('20190225' as date)
select count(dateadd(dd,number,#d)) from master..spt_values
where type = 'p'
and month(dateadd(dd,number,#d))=month(#d)
and year(dateadd(dd,number,#d))=year(#d)
and cast(GETDate() as date)>= Cast(dateadd(dd,number,#JoinDate) as date )
The result of above code is 28 but I want 4
Please help me to find the expected result
This is simple date arithmetic, you do not need to use spt_values:
declare #d date = '20190225';
select datediff(month,0,#d) as MonthsDiff -- Months since an arbitrary date
,dateadd(month,datediff(month,0,#d)+1,0) as StartOfFollowingMonth -- Add months above +1 to same arbitrary date
,datediff(day,#d,dateadd(month,datediff(month,0,#d)+1,0)) as DaysBetweenGivenDate -- DATEDIFF between given date and start of month from above;
Output:
+------------+-------------------------+----------------------+
| MonthsDiff | StartOfFollowingMonth | DaysBetweenGivenDate |
+------------+-------------------------+----------------------+
| 1429 | 2019-03-01 00:00:00.000 | 4 |
+------------+-------------------------+----------------------+
Try this:
declare #date date='20140603'
select datediff(day, #date, dateadd(month, 1, #date))-day(#date)
Starting with SQL Server 2012, you could just use the EOMONTH function:
SELECT DATEDIFF(DAY, '20190225', EOMONTH ('20190225')) + 1 [thedays]
= 4.
I need date format in American Format i.e. 9/30/2018; 8/31/2018; 7/31/2018.. so on and so forth in SSIS. I have written the code in the format as
LEFT((DT_STR,50,1252)DATEADD("d",-DAY(GETDATE()),GETDATE()),10)
This is bringing date in 2018-09-30 which is not the proper format. I do have given the data type as "STRING" as the above code doesn't take "DATE/DATE-TIME" as data type.
I am trying to bring the previous month last date and hence the format currently being fetched is not right.
Any guesses?
Thanks!
For a format like this, the date parts will need to be extracted from the date and concatenated accordingly. The expression below will convert the date to the DD/MM/YYYY format. Since you only listed single digits for the month in your question, this example does not account for zeros and the length will vary. If you want zeros added to single digit days and months, a "0" (with quotes) will need to be appended before the day and month.
RIGHT((DT_STR, 2, 1252) DATEPART("MM", DATEADD("D",-DAY(GETDATE()),GETDATE())), 2)
+ "/" + RIGHT((DT_STR, 2, 1252) DATEPART("DD", DATEADD("D",-DAY(GETDATE()),GETDATE())), 2)
+ "/" + (DT_STR, 4, 1252) DATEPART("YYYY", DATEADD("D",-DAY(GETDATE()),GETDATE()))
How about that
DECLARE #AsStr VARCHAR(10) = '2018-09-30', --If you store it as string
#AsDate DATE = '2018-09-30'; --If you store it as date
SELECT CONVERT(VARCHAR(10), #AsDate, 101) AsStr,
CONVERT(VARCHAR(10), CAST(#AsStr AS DATE), 101) AsDate;
Returns
+------------+------------+
| AsStr | AsDate |
+------------+------------+
| 09/30/2018 | 09/30/2018 |
+------------+------------+
Or you can use FORMAT() function as
SELECT
FORMAT(CAST(#AsStr AS DATE), 'MM/dd/yyyy') FormatStr,
FORMAT(#AsDate, 'MM/dd/yyyy') FormatDate;
Returns
+------------+------------+
| FormatStr | FormatDate |
+------------+------------+
| 09/30/2018 | 09/30/2018 |
+------------+------------+
You can use DATEFROMPARTS to get the first day of the month fairly easily. Then, you can use DATEADD to subtract a day, then CONVERT to output the 101 format which is in the form MM/DD/YYYY.
For example:
DECLARE #DT_STR Date = '2018-10-23'
SELECT CONVERT(varchar, DATEADD(DAY, -1, DATEFROMPARTS(YEAR(#DT_STR), MONTH(#DT_STR), 1)), 101) AS [answer]
Produces output:
answer
09/30/2018
I have a string field in database named "ExamDate" which contains dates. Initially, the application had no front-end validation in place and database was saving as string, so users were able to input dates in any format.
The required format is DD-MMM-YYYY but currently the field has values in all formats, like:
14-Jun-2017
9/15/2017
May 2017
February 1, 2017
NULL value
I have to display this field in a DB view and convert all of them into date format.
The various options I tried give me errors like:
"a non-numeric character was found where a numeric was expected" or
"invalid number"
I also realized that the "day" field is missing in a few of the dates, like 'May 2017' which needs to be set to 01-May-2017.
Do you suggest going ahead with a solution similar to one pasted below from path: How to update dates stored as varying character formats (PL/SQL)?
SELECT ANTICIPATEDSPUD
,DECODE (
INSTR (ANTICIPATEDSPUD, '-')
,5, TO_DATE (ANTICIPATEDSPUD, 'YYYY-MM-DD')
,3, TO_DATE (ANTICIPATEDSPUD, 'MM-DD-YYYY')
,DECODE (LENGTH (ANTICIPATEDSPUD)
,8, TO_DATE (ANTICIPATEDSPUD, 'MM/DD/YY')
,10, TO_DATE (ANTICIPATEDSPUD, 'MM/DD/YYYY')))
FROM FSW_BASIC_WELL_INFO_VW;
Perhaps you could try to group data that share the same format. REGEXP_LIKE might be handy in such a case. It might be OK as it allows you to "upgrade" it easily, as soon as you find yet another format people used to enter data.
The following example certainly isn't ideal because of typos; months could have been "Ferubrary" or "Mya"; days could be 35, months 13 and so forth so you'd have to check whether those values are meaningful.
Anyway; have a look. I've included the ID column just for sorting purposes.
SQL> alter session set nls_date_language = 'english';
Session altered.
SQL> alter session set nls_date_format = 'dd.mm.yyyy';
Session altered.
SQL> with test (id, datum) as
2 (select 1, '14-Jun-2017' from dual union
3 select 2, '9/15/2017' from dual union
4 select 3, 'May 2017' from dual union
5 select 4, 'February 1, 2017' from dual union
6 select 5, null from dual
7 )
8 select id, datum, to_date(datum, 'dd-mon-yyyy') result from test
9 where regexp_like(datum, '[0-9]{1,2}-[[:alpha:]]{3}-[0-9]{4}')
10 union
11 select id, datum, to_date(datum, 'mm/dd/yyyy') from test
12 where regexp_like(datum, '[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}')
13 union
14 select id, datum, to_date(datum, 'mon yyyy') from test
15 where regexp_like(datum, '[[:alpha:]]{3} [0-9]{4}')
16 union
17 select id, datum, to_date(datum, 'month dd, yyyy') from test
18 where regexp_like(datum, '\w+ [0-9]{1,2}, [0-9]{4}')
19 order by id;
ID DATUM RESULT
---------- ---------------- ----------
1 14-Jun-2017 14.06.2017
2 9/15/2017 15.09.2017
3 May 2017 01.05.2017
4 February 1, 2017 01.02.2017
SQL>
I have an issue retrieving the data that I would like. I have a Varchar column that consist of various information. I would like to extract the date from that column only. However, I have been unsuccessful. I used the following SQL(2008) to get the data below, But I can't seem to just get the date only without the time. Obviously, the date and time are in different position. Hope you can help.
SELECT substring(Data, 8, 17)
from mastInfo
9/25/2013 12:36:5
Jul 8 2013 11:40
9/25/2013 12:43:5
SELECT convert(date, Case When IsDate(substring(Data, 8, 17)) = 1
Then substring(Data, 8, 17)
Else NULL END)
from mastInfo
Since you are starting off with a string, it is possible that it does not represent a valid date. Using the IsDate function will return 1 when the string can be converted to a date. Basically, this code will convert to date those values that can be converted, and will return NULL for those values that cannot be converted to a valid date.
If you are using SQL Server 2012 or newer, then you can use Try_Convert().
Here's the SQL Fiddle.
Here's an example (from the above SQLFiddle):
Select Try_Convert(datetime, DateAsString) As DateAsDateTime
,DateAsString
From SomeTable
Here's the result:
DATEASDATETIME DATEASSTRING
September, 25 2013 12:36:05+0000 9/25/2013 12:36:5
September, 25 2013 12:43:05+0000 9/25/2013 12:43:5
July, 08 2013 11:40:00+0000 Jul 8 2013 11:40
if you want convert it to date time use :
SELECT CONVERT(Datetime, '2011-09-28 18:01:00', 120) -- to convert it to Datetime
if you want get time :
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), '2011-09-28 18:01:00', 100), 7))
if you want date part :
SELECT CONVERT (DATE, GETDATE())
what version of sql server?
can you try this:
SELECT convert(date, substring(Data, 8, 17))
from mastInfo
First convert Varchar into DateTime and after that again convert it in varchar in desired date format like 101,102,103
Try this:
select convert(varchar(50),convert(datetime,'9/25/2013 12:43:5'),101)