Convert Decimal or Varchar into Date - sql

I have 2 fields.
Birth= Datatype Decimal(12,4) & Date = Datatype Date
Birth Date
19650101 2015-07-09
how do i get a result that looks like this
i want the result to be like this
Birth Date
1965-01-01 2015-07-09
where the Birth is a Date datatype and not a decimal (12,4)

To convert the number 19650101 to a date use
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112)
To get the number of years (to one decimal) you could do:
ROUND(
DATEDIFF(day,
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112),
[Date])/365.25
,1)
Which won't be exact but should be close enough to tenths of a year.

You can use this:
-- Create demo data
CREATE TABLE #dates(birth int, date date)
INSERT INTO #dates(birth,date)
VALUES(19650101,N'2015-07-09')
-- Your work
SELECT CONVERT(date,CONVERT(nvarchar(max),birth),112) as birth, date,
DATEDIFF(year,
CONVERT(date,CONVERT(nvarchar(max),birth),112),
date
) as years
FROM #dates
-- Cleanup
DROP TABLE #dates
This depends on the exact format you provides (19650101).

Here is one way to do this conversion.
cast(cast(FLOOR(birth) as CHAR(8)) as DATE)

I think you don't need to round. Just convert your decimal value and put "-" like below : )
select left(birth,4) +'-' +
substring(convert(nvarchar,birth),5,2)+'-'+
substring(convert(nvarchar,birth),7,2)

Related

Convert varchar to date without timestamp

I am trying to convert/select the nvarchar datatype to date format (YYYY-MM-DD).
The table contains the date in DD/MM/YYYY format & also the null values.
Below SQL query is working fine but it has timestamp in the output
select Date4 = Convert(datetime, Last_Paid_Date, 103) FROM table
2021-01-30 00:00:00.000
My requirement is to have only the date in (YYYY-MM-DD) format
normally this should work
select Convert(date, Last_Paid_Date, 103) from tablename
But if you get conversion errors you can try this
SELECT convert(date, convert(datetime, Last_Paid_Date, 103)) FROM TableName
if Date cannot be used to convert from your format, the trick is to convert to a datetime first, and then convert that into a date.
Much much better would be to store the data in a column with type Date instead of varchar off course
I find this also some good reading
EDIT
if you keep getting conversion errors, then probably there are invalid dates in your varchar column. That is why you should never never never store dates/time in a varchar column.
To fix this, you could use this
SELECT try_Convert(date, Last_Paid_Date, 103) from tablename
this will put NULL in all columns that have an invalid date/time.
Drawback is that from all the rows that will have a value NULL, you cannot know if the original value was also NULL or an invalid date/time value.
Please try the below.
SELECT Date4 = CONVERT(DATE, Last_Paid_Date, 103) FROM TableName
OR
SELECT Date4 = CAST(GETDATE() AS DATE) FROM TableName
This will remove the Timestamp and give you only the Date values in the (YYYY-MM-DD) format.
You can go for simple conversion.
SELECT Convert(date, '20/01/2020', 103)
2020-01-20
You can go for conversion for the table as given below:
SELECT Convert(date, val, 103) as dateval FROM
(
values
('20/01/2020'),(null)
) as t(val)
dateval
2020-01-20
NULL
The issue with your query is that the column: "Last_Paid_Date" contains NULL String, which needs the conversion as they are characters.
You can try the below query:
SELECT convert(date, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
, convert(datetime, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
FROM table
The query will replace the NULL strings with a default value if any and then do the date/datetime conversions accordingly
You can chain two conversions : the first one converts the original dd/mm/yyyy (103) to a datetime value, and the second conversion turns that datetime into a yyyy-mm-dd (120) string.
select Date4 = convert(varchar(10), convert(date, Last_Paid_Date, 103), 120)
from table

how to get this results for this?

Write a SELECT statement that returns these columns from the db1.MyGuitarShop.Products table:
a) The DateAdded column
b) A column that uses the CAST function to return the DateAdded column with its date only (year, month, and day)
c) A column that uses the CAST function to return the DateAdded column with its full time only (hour, minutes, seconds, and milliseconds)
d) A column that uses the CAST function to return the DateAdded column with just the month and day
This is what I have currently:
SELECT
DateAdded,
CAST(DateAdded AS decimal(10, 1)) AS AddedDate,
CAST(DateAdded AS decimal(10)) AS AddedTime,
CAST(DateAdded AS int) AS AddedChar7
FROM MyGuitarShop.Products;
With CAST converting to a DATE and TIME is easy. But the third item is trickier and involves two separate CASTS's, followed by string concatenation.
Something like this shoul do the trick:
Note that I've subbed in a variable (#dt) just to make it simpler to demonstrate the concept.
DECLARE #dt DATETIME = GETDATE()
SELECT #dt
, CAST(#dt AS Date) AS AddedDate
, CAST(#dt AS Time) AS AddedTime
, CAST(MONTH(#dt) AS VARCHAR(4)) + CAST(DAY(#dt) AS VARCHAR(4)) AS AddedChar
Here is a fiddle
Another options would be to use CONVERT to convert the dates to text. It has the advantage of allowing you to choose a specific format for the results ...
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15
SELECT
DateAdded,
CONVERT(varchar(128), DateAdded, 111) AS AddedDate,
CONVERT(varchar(128), DateAdded, 14) AS AddedTime,
CAST(DATEPART(MONTH, DateAdded) as varchar(2)) + '/' + CAST(DATEPART(DAY, DateAdded) as varchar(2)) AddedChar7
FROM (VALUES
(GETDATE())
)Products(DateAdded)
SELECT DateAdded
,Cast(DateAdded as date) Cast_YMD --Default for date is YMD
,Cast(DateAdded as time) Cast_HMSM -- Default for time is HMSM
,CAST(DateAdded as char(6)) Cast_MMDD --The 6 characters in the date field are month(as 3 char name Jan,Feb...) and day(as 2 digit)
FROM Products

How to convert string in 'DD/MM/YYYY' or 'YYYY-MM-DD' into date in SQL Server?

I've got a string here which needs to be converted into date but the problem is that it could either be in 'DD/MM/YYYY' or 'YYYY-MM-DD' format.
I've already tried convert which only works for one of the two formats but not both:
declare #string nvarchar(255) = '2019-05-21'
declare #table table (date date)
insert into #table
select convert(date, #string, 111) as date
select * from #table
declare #string nvarchar(255) = '21/05/2019'
declare #table table (date date)
insert into #table
select convert(date, #string, 103) as date
select * from #table
Both of the above solutions result in an error is I use the other format.
Is there a way to get a string converted to date regardless of what format it is in?
Use try_convert():
insert into #table
select coalesce(try_convert(date, #string, 111),
try_convert(date, #string, 103)
) as date
try_convert() returns NULL if the conversion fails. In that case, the conversion will move on to the next pattern. With coalesce(), you can have as many different formats as you like.
You can use TRY_PARSE or PARSE to parse the date literal using a specific culture.
The second format YYYY-MM-DD is an unambiguous date format for the "new" date types like date and datetime2. It's not affected by the DATEFORMAT setting like datetime.
This means you only need to find one culture that can handle the first format. All of the following queries will return the same value :
select parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
select try_parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select try_parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
If you are on SQL 2012 and above, you can use the FORMAT function.
The signature of this function is - FORMAT (value,format[,culture])
Example: SELECT FORMAT (getdate(), 'dd-MM-yyyy') as date and in your case SELECT FORMAT(CAST(<str_value> as DATE), 'yyyy-mm-dd')

Convert ISO-8601 varchar (0000-00-00T00:00:00+00:00) to datetime in SQL

How can I convert 2019-07-01T00:00:00+05:30 to DateTime in SQL?
2019-07-01T00:00:00+05:30 is a varchar field. I need to convert this into DateTime to compare this to a date field.
suggest me a query to Convert (2019-07-01T00:00:00+05:30) into DateTime
Convert To date :
select cast('2019-07-01T00:00:00+05:30' as Date)
Convert To time:
select cast('2019-07-01T00:00:00+05:30' as Time)
Convert To datetime :
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
Try any of these..
select cast(convert(datetime2, '2019-07-01T10:00:30+05:30',0) as datetime)
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
One option would be to use a combination of CONVERT on the timestamp without the timezone component, then use TODATETIMEOFFSET with the timezone portion to get the final result:
WITH yourTable AS (
SELECT '2019-07-01T00:00:00+05:30' AS dt
)
SELECT
TODATETIMEOFFSET(CONVERT(datetime, LEFT(dt, 19), 126), RIGHT(dt, 6)) AS output
FROM yourTable;
This outputs:
01/07/2019 00:00:00 +05:30
Demo
Unfortunately, SQL Server truncates the time zone information when converting from datetimeoffset to dateordatetime`. But, you can calculate the offset and add it back in:
select dateadd(minute,
datediff(minute, convert(datetimeoffset, dt), convert(datetime, convert(datetimeoffset, dt))),
convert(datetime, convert(datetimeoffset, dt))
)
from (values ('2019-07-01T00:00:00+05:30')) v(dt);
For your particular timezone, the date at midnight matches the UTC date, so you are safe. I'm on the other side of the world, so this would be a more important consideration in the "western" world ("west" being west of UTC).
The following query will convert the given VARCHAR to DATETIME value:
DECLARE #DateVal AS VARCHAR (30) = '2019-07-01T00:00:00+05:30';
SELECT CAST(REPLACE(SUBSTRING(#DateVal, 0, CHARINDEX('+', #DateVal)), 'T', ' ') AS DATETIME);

SQL Output to get only last 7 days output while using convert on date

I am using the below SQL Query to get the data from a table for the last 7 days.
SELECT *
FROM emp
WHERE date >= (SELECT CONVERT (VARCHAR(10), Getdate() - 6, 101))
AND date <= (SELECT CONVERT (VARCHAR(10), Getdate(), 101))
ORDER BY date
The data in the table is also holding the last year data.
Problem is I am getting the output with Date column as
10/11/2013
10/12/2012
10/12/2013
10/13/2012
10/13/2013
10/14/2012
10/14/2013
10/15/2012
10/15/2013
10/16/2012
10/16/2013
10/17/2012
10/17/2013
I don't want the output of 2012 year. Please suggest on how to change the query to get the data for the last 7 days of this year.
Instead of converting a date to a varchar and comparing a varchar against a varchar. Convert the varchar to a datetime and then compare that way.
SELECT
*
FROM
emp
WHERE
convert(datetime, date, 101) BETWEEN (Getdate() - 6) AND Getdate()
ORDER BY
date
Why convert to varchar when processing dates? Try this instead:
DECLARE #Now DATETIME = GETDATE();
DECLARE #7DaysAgo DATETIME = DATEADD(day,-7,#Now);
SELECT *
FROM emp
WHERE date BETWEEN #7DaysAgo AND #Now
ORDER BY date
Use this, simply.
Select columnname
from tablename
WHERE datecolumn> dateadd(day,-7,GETDATE())