Convert Varchar field to datetime in SQL Server - sql

I am trying to convert varchar date to date time field and having a really hard time. It is giving me:
Conversion failed when converting date and/or time from character string.
or
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I have 2 datetime formats below :
Date field looks like 21-12-2009, 05-10-2005 etc
Date field looks like 19-03-2018 14:59
select cast(convert(varchar,Stg_hw.date_of_birth,110)as date)
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
select CONVERT(datetime,LEFT(date_of_birth,2)+SUBSTRING(Stg_hw.date_of_birth,4,2)+SUBSTRING(Stg_hw.date_of_birth,7,4))
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
select cast(Stg_hw.date_of_birth as date)
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458

CONVERT(DATETIME, DateFieldColumnName, 103) can help to convert those 2 format to datetime.
Sample exection:
CREATE TABLE TestTable (DateVal VARCHAR (20));
INSERT INTO TestTable (DateVal) VALUES
('21-12-2009'), ('05-10-2005'), ('19-03-2018 14:59');
SELECT CONVERT(DATETIME, DateVal, 103) AS Result
FROM TestTable
Please find the working demo on db<>fiddle

Related

Converting a varchar column to datetime

I have a table that has a column for dateofbirth varchar(10). All the data inside is stored like this '02/01/1990'.
I need to convert it to datetime. I've tried
CAST(DateofBirth AS DATEITME) AS BirthDate
But I keep getting this error when I try importing:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value"
I need it like this:
1990-02-01 00:00:00:000
SELECT CONVERT(Datetime, '2011-09-28 18:01:00', 120) -- to convert it to Datetime SELECT CONVERT( VARCHAR(30), #date ,105) -- italian format [28-09-2011 18:01:00] + ' ' + SELECT CONVERT( VARCHAR(30), #date ,108 ) -- full date [with time/minutes/sec]
You need to convert a Varchar in format MM/DD/YYYY to a Datetime.
Sql server recognizes a set of predefined date formats that it is able to automatically parse. See this cheat list.
Your input format corresponds to sql server date format 101, hence you can do :
SELECT CONVERT(Datetime, '02/01/1990', 101)
If you try to do it in sql query there is syntax to do it .
Here a link ..
SQL Server Convert Varchar to Datetime
Your cast statement works for me:
Declare #dateofbirth varchar(10) = '02/01/1990'
select cast(#dateofbirth as datetime)AS BirthDate
Result:
BirthDate
1990-02-01 00:00:00.000

Dutch varchar date issue in SQL server 13 month

I have the following datetime format ( as varchar ) in my database 13-04-2018 1:05:00.
I need to convert it to the following format: 2018-04-13 01:05:00. As datetime.
Normal convert functions can't do this because they try to take the 13th month, and that month doesn't exist. This error:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
Does someone know how to convert this date issue?
Using datetimes is always a pain regardless of the language because of all the different formats across the world.
To sort your issue out currently, you need to use a format style which is a third parameter to CONVERT. Personally what I would suggest here is to store as a datetime, because storing datetimes as strings is never a good idea. It just gets too messy later on, but if saved in the format you would like, it would be saved as yyyy-MM-dd hh:mm:ss
SELECT CONVERT(DATETIME, '13-04-2018 1:05:00',103)
You can create your own function to format it in your desired output string.
CREATE FUNCTION FormatMyDate
(#Date DATETIME) RETURNS VARCHAR(20)
AS
BEGIN
RETURN FORMAT(#Date,'yyyy-dd-MM hh:mm:ss')
END
And then you can call it in SELECT statements like this:
SELECT dbo.FormatMyDate(yourDateCol)
FROM yourTable
this takes the date from the format where month comes before day and reverses the 2 values (month and day)
SELECT CONVERT(DATETIME, '2018-13-04 01:05:00', 103);
Results:
2018-04-13 01:05:00.000
This should work for you requirement...
SELECT FORMAT(yourdate, 'yyyy-dd-MM')
Your Solution Bro...
DECLARE #d DATETIME = GETDATE()
SELECT FORMAT ( #d, 'MM-dd-yyyy hh:mm:ss', 'de-de' ) AS 'Hoping your result'

SQL Server: how to change data entry from VARCHAR to DATETIME?

I have below sample data:
03202012 as date but the column datatype is Varchar.
I want to convert it to 2012-03-20 00:00:00.000 as Datetime.
I tried using
CAST(CONVERT(CHAR(10), Column, 101) AS DATETIME)
But I get an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Complete code snippet to test:
DECLARE #Column VARCHAR(MAX) = '03202012'
SELECT CAST(CONVERT(CHAR(10), #Column, 101) AS DATETIME)
Use yyyyMMdd format, that always works:
DECLARE #myDateString varchar(10) = '03202012';
SELECT cast( substring(#myDateString, 5, 4)+
substring(#myDateString, 1, 2)+
substring(#myDateString, 3, 2) AS datetime);
I found below script help me solved my concern.
SELECT convert(datetime, STUFF(STUFF('31012016',3,0,'-'),6,0,'-'), 105)
Result: 2016-01-31 00:00:00.000
Thanks all for the effort. :D
In MySQL, you can use the STR_TO_DATE function to convert a string to a date. For your example, it would look like this
STR_TO_DATE("03-02-2012", "%m-%d-%Y");
Note that the format part of the string must match the format part of the date.
Edit: Just found out this is for SQL Server, but I assume this will work there as well.

How to update/Change the date format to MM/dd/yyyy from dd/MM/yyyy format in sql server?

In my db DOB is saved in dd/mm/yyyy format. i want to change the DOB date format to MM/dd/yyyy. How can i do that?
First i want to know which datatype you are using for saving your date value. There is nothing provided with your code no sample code, table details nothing. anyway
i think your 'date of birth' field datatype is datetime,then you can use the following example
create table checktable(
ID int,
name nvarchar (30),
dob datetime);
Example data insert into the table
insert into checktable(ID,name,dob) values(10,'myname','03/01/2014');
//..........
select * from checktable
//Use CONVERT() it will give you the desired output
SELECT TOP 1 ID, dob,CONVERT(varchar,dob,101) 'mm/dd/yyyy'
FROM checktable
UPDATE
if your datatype is varchar and now it is in the format mm/dd/yyyy and you want to change it into dd/mm/yyyy format then use the following example it will help you
create table checktable1(
ID int,
name nvarchar (30),
dob varchar(20));
// insert sample data
insert into checktable1(ID,name,dob) values(10,'myname','21/05/2010');
select * from checktable1
// change the format using substring()
select * FROM checktable1
select dob,substring(dob,4,3)+substring(dob, 1, 3)+substring(dob, 7, 4) from checktable1
It will give you result in 05/21/2010 (mm/dd/yyyy)format
Microsoft SQL: https://msdn.microsoft.com/en-us/library/ms187928.aspx
Syntax for CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
use example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]
For other databases search Date and Time Functions in documentation.
The CONVERT() function is a general function that converts an expression of one data type to another.
The CONVERT() function can be used to display date/time data in different formats.
http://www.w3schools.com/sql/func_convert.asp
if your data type is DateTime then no need to convert it, in later you can convert its format as you want but if your are using varchar or nvarchar
then you can use CONVERT() as below
SELECT convert(datetime, '23/10/2016', 103)
Result : 2016-10-23 00:00:00.000
if just want to conver in date then
SELECT convert(date, '23/10/2016', 103)
Result : 2016-10-23
for more information and other formats
http://www.sqlusa.com/bestpractices/datetimeconversion/
and if you just want to convert string to sting then
SELECT CONVERT(varchar,'23/10/2016',101)
Result : 23/10/2016
This is the query to show all data in dd/mm/yyyy format.Type your column name that contains date in place of datecolumnname and your table name in place of tablename in below query:
select convert(varchar,datecolumname,103) as datecolumname from tablename

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I have a table with a column that stores the date and time. I need to write a query to get only the date from that column,
SELECT CAST(CONVERT(VARCHAR, LoginTime, 101) AS datetime) FROM AuditTrail
But, when I run the query I am getting this error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
the data in the column is datetime ex: 2012-06-18 12:08:04.000
so i need to extract the date only and remove the time
note that the [Logintime] column is datatime format
Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
WHERE ISDATE(LoginTime) = 1
Click here to view result
EDIT :
As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT
SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail
or
SELECT LEFT(LoginTime,10) FROM AuditTrail
EDIT 2 :
The major reason for the error will be in your date in WHERE clause.ie,
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('06/18/2012' AS DATE)
will be different from
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('18/06/2012' AS DATE)
CONCLUSION
In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.
hope this may help you:
SELECT CAST(LoginTime AS DATE)
FROM AuditTrail
If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month
as you can see on the answer to this question:
Conversion of a varchar data type to a datetime data type resulted in an out-of-range value
-- set the dateformat for the current session
set dateformat dmy
-- The conversion of a varchar data type
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31' as datetime)
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = ##spid
-- set the dateformat for the current session
set dateformat ymd
-- this should work
select cast('2017-08-13 16:31:31' as datetime)
I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.
The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.
some problem, but I find the solution, this is :
2 February Feb 28 (29 in leap years)
this is my code
public string GetCountArchiveByMonth(int iii)
{
// iii: is number of months, use any number other than (**2**)
con.Open();
SqlCommand cmd10 = con.CreateCommand();
cmd10.CommandType = CommandType.Text;
cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, #start, 103) and CONVERT(VARCHAR, #end, 103)";
cmd10.Parameters.AddWithValue("#start", "" + iii + "/01/2019");
cmd10.Parameters.AddWithValue("#end", "" + iii + "/30/2019");
string result = cmd10.ExecuteScalar().ToString();
con.Close();
return result;
}
now for test
lbl1.Text = GetCountArchiveByMonth(**7**).ToString(); // here use any number other than (**2**)
**
because of check **February** is maxed 28 days,
**