Suppose I have a table storing a list of datetime (yyyyMMdd) in String format.
How could I extract them and convert them into DateTime format dd/MM/yyyy ?
e.g. 20120101 -> 01/01/2012
I have tried the following:
var query = from tb in db.tb1 select new { dtNew = DateTime.ParseExact(tb.dt, "dd/MM/yyyy", null); };
But it turns out the error saying that the ParseExact function cannot be recgonized.
It's probably worth just doing the parsing locally instead of in the database, via AsEnumerable:
var query = db.tb1.Select(tb => tb.dt)
.AsEnumerable() // Do the rest of the processing locally
.Select(x => DateTime.ParseExact(x, "yyyyMMdd",
CultureInfo.InvariantCulture));
The initial select is to ensure that only the relevant column is fetched, rather than the whole entity (only for most of it to be discarded). I've also avoided using an anonymous type as there seems to be no point to it here.
Note how I've specified the invariant culture by the way - you almost certainly don't want to just use the current culture. And I've changed the pattern used for parsing, as it sounds like your source data is in yyyyMMdd format.
Of course, if at all possible you should change the database schema to store date values in a date-based column, rather than as text.
As already said, it's better to store date as date-type column in your DB, but if you want just to convert strings from one format to another, you can do this:
db.tb1.Select(x => String.Format("{0}/{1}/{2}", x.Substring(6, 2), x.Substring(4, 2), x.Substring(0, 4))
Create a UDF in SQL Server and then import to your linq to sql project and use in the comparison
-- =============================================
-- Author:
-- Create date:
-- Description: Convert varchar to date
-- SELECT dbo.VarCharAsDate('11 May 2016 09:00')
-- =============================================
CREATE FUNCTION VarCharAsDate
(
-- Add the parameters for the function here
#DateAsVarchar NVarchar(100)
)
RETURNS DateTime
AS
BEGIN
-- Declare the return variable here
if IsDate(#DateAsVarchar) = 1 BEGIN
-- Return the result of the function
RETURN convert(datetime, #DateAsVarchar, 109)
END
RETURN NULL
END
GO
then in code
.Where(p => ValueDateTime > db.VarCharAsDate(p.Value))
Related
For one the production system, different date/time format I am getting data time like 11.22.2022 09.10.00 and when try to run below sql query I am getting error The conversion of a varchar data type to a datetime data type resulted in an out-of-range value,
I tried to convert date before querying SQL like '{ac.LastCollectionTime:MM/dd/yyyy HH:mm:ss}'),"), but it's not converting.
DECLARE #data TABLE(Id uniqueidentifier, Value DateTime)
INSERT INTO #data VALUES ('57f5a153-3cce-48d4-aa0d-894c14b1a2ab', '11.22.2022 09.10.00')
UPDATE A SET LastCollectionTime = AD.Value
FROM App A INNER JOIN #data AD on AD.Id = A.Id
How to fix this issue?
As this is not a date string format SQL Server is aware of out the box, you will either need to adjust your data source to provide an appropriate format or parse out the bits you need manually.
One such way of doing this is as follows:
create table d(ds varchar(25));
insert into d values
('11.22.2022 09.10.00')
,('11.01.2022 01.01.01');
select d.ds
,datetime2fromparts(dp.y,dp.mo,dp.d,dp.h,dp.mi,dp.s,0,0) as dt
from d
cross apply(values(substring(d.ds,7,4)
,substring(d.ds,1,2)
,substring(d.ds,4,2)
,substring(d.ds,12,2)
,substring(d.ds,15,2)
,substring(d.ds,18,2)
)
) as dp(y,mo,d,h,mi,s)
Which outputs:
ds
dt
11.22.2022 09.10.00
2022-11-22 09:10:00
11.01.2022 01.01.01
2022-11-01 01:01:01
I am trying to serialize an entity using XML serialization on SQL. Unfortunately I notice that my datetime is not properly read. I am returning a 24 hour format, but on SQL, its reading a different time. Here is the exact SQL Stored Procedure:
DECLARE
#XML XML = '- <ArrayEntityView>
- <entEntity>
<dtModifiedDate>2017-07-24T14:09:20.4483795+08:00</dtModifiedDate>
</entEntity>
</ArrayEntityView>'
DECLARE #tblProcAssign TABLE
(
dtmoddate DATETIME
)
INSERT INTO #tblProcAssign
(
dtmoddate
)
SELECT entuserunits.value('dtModifiedDate[1]', 'DATETIME') AS dtModDate
FROM #XML.nodes('ArrayEntityView/entEntity')entUserUnits(entuserunits)
select * from #tblProcAssign
Based on the code above, I am passing a date:
2017-07-24T14:09:20.4483795+08:00
But on SQL, its reading is:
2017-07-24 06:09:20.447
And I am not sure why, it should be:
2017-07-24 14:09:20.447
The data came from c# code DateTime.Now. I don't want to use GetDate in SQL since sometimes, I am not using DateTime.Now. How should I format this entity or any parsing I need to do so that I will get my expected result?
You need to switch the data type from datetime to datetimeoffset if you want time zone information to be recognised. Without it, only the actual time value (that is, UTC) is returned.
Make sure that the data type is replaced in both the table definition and the XML value() method:
DECLARE #tblProcAssign TABLE (dtmoddate datetimeoffset);
INSERT INTO #tblProcAssign (dtmoddate)
SELECT entuserunits.value('dtModifiedDate[1]', 'datetimeoffset') AS dtModDate
FROM #XML.nodes('ArrayEntityView/entEntity')entUserUnits(entuserunits);
I have a variable which is datetime type. How can i get the shortdatetostring() as datetime variable type ? I have a column in databae as datetime type. I would like to get the records which are added at a certain day.
Example:
SELECT id FROM database WHERE added like #p1
The parameter of the query is a datetime variable.
Match based on day, month, and year of the date variables. Do not use strings, since matching is slow.
SELECT id
FROM database
WHERE Datepart(yy, added) = Datepart(yy, #p1)
AND Datepart(mm, added) = Datepart(mm, #p1)
AND Datepart(dd, added) = Datepart(dd, #p1)
You could do something like this in order to get all the ids on the 26th of January.
SELECT id FROM database WHERE added >= '2012-01-26' and added < '2012-01-27'
In C# you do like below.
DateTime dt;
string Temp1 = "Your Date";
if (DateTime.TryParse(Temp1, out dt))
{
// If it is a valid date
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
}
In SQL Server
SELECT id FROM database WHERE Datepart(dd, added) = Datepart(dd, #p1)
Please see below the sample
create table #temp
(
dat datetime,
)
insert into #temp(dat)values(GETDATE())
insert into #temp(dat)values(GETDATE()+1)
insert into #temp(dat)values(GETDATE()+2)
select * from #temp where DATEPART(dd, dat) > 27
drop table #temp
If you are using parameterised queries the format of the datetime type doesn't matter.
Got to remember that "2012-01-26" is a string not a date....
If you need a Date formatted a particular way, then myDateTime.ToString(....), there are several overloads, one of which is simply a format String e.g. "yyyy-MM-dd"
If you want to parse a string into a datetime then DateTime.Parse(...), again there are several overloads.
More on dates after comment
DateTime.Parse("12/31/2012") gives you a datetime type in c#.
It parses the string into a DateTime
MyDateTime.ToString("MM/dd/yyyy") gives you a string of date in the specified format.
"31/12/2012" is not a date, if you want it as a date, then you Parse it into one.
Now which way do you want to go DateTime to a string, or string to a DateTime, or are you asking something completely different?
If you want to only Parse DateTimes trhat are in the format mm/dd/yyyy, you can't because when it's string there's absolutely no way to tell the 6th of August from the 8th of June, unless you assume the format is always mm/dd/yyyy which is pretty much guaranteed to go badly wrong at somepoint, which is why when going from Date to String YYYYMMDD or YYYY-MM-DD are the way to go.
If it's what you want / have to do then
DateTime MyDateTime = DateTime.Parse("12/31/2012",CultureInfo.CurrentCulture);
Pass a string in a format that doesn't fit the pattern and it will throw an exception, NB that would include "31/12/2012".
CultureInfo is in the System.Globalisation namespace.
There area number of options. Current, CurrentUI, Invariant etc. Which one you use depends on how you are setup and globalisation / internationalisation requirements (even if they are none). So using Current Culture, would assume US default regional settings. But if I was to run your code, then "31/12/2012" would work and "12/31/2012" would blow chunks.
If you want to fix the formats no matter what system they are run on then InvariantCulture is the way to go. Don't forget to set the neutral language as well. Hit the assembly button on the Applications tab of the project's property pages. Neutral language is a drop down near the bottom. Presumably you want en-us.
If you don't want the excpetion then it's
DateTime myDateTime;
if (DateTime.TryParse("12/31/2012",CultureInfo.CurrentCulture, out myDateTime)
{
// do something with myDateTime...
}
else
{
// do something about the value not being in the correct format
}
You might be able to simplify this by editing the query, actually. Try
select id from database where cast(added as date) = cast(#p1 as date)
This (effectively) strips the time from added as well as the time from #p1 and compares the dates only.
I have a dateTime object in C# and i want to do an insert into SQL Server datetime field. What is the correct format for this?
The correct way to do this is by using a parameterised query, not text formatting. Then you can just use a strongly-typed SqlDbType.DateTime parameter.
(If you absolutely must use text formatting to do this - and I strongly recommend against it - then something like yyyyMMdd HH:mm:ss should do the trick.)
To expand on #Luke's answer I came across this bug just the other day.
The yyyy-MM-dd HH:mm:ss format has a locale/language issue on SQL Server 2005 (an example is French), but is fixed in SQL 2008:
So, do NOT use this format: yyyy-MM-dd HH:mm:ss (space separator).
Only use: yyyy-MM-ddTHH:mm:ss ("T" separator) or yyyyMMdd HH:mm:ss (no dash delimiters)
Important if you're generating scripts that include datetime constants.
See Jamie Thomson's article on SQL Blog
use SET DATEFORMAT
a sample took from here
SET NOCOUNT ON
CREATE TABLE X(EXAMPLE INT, D SMALLDATETIME)
-- EXAMPLE 1
SET DATEFORMAT MDY
INSERT INTO X VALUES (1, '10/30/56')
-- EXAMPLE 2
SET DATEFORMAT YDM
INSERT INTO X VALUES (2, '56/31/10')
-- EXAMPLE 3
SET DATEFORMAT YMD
INSERT INTO X VALUES (3, '56/10/31')
SELECT * FROM X
I'm having a problem with some T-SQL in a SP on SQLServer 2005 comparing dates. I'm running the stored procedure from c# with ADO.Net and passing a the native c# datetime datatype(could this be my issues as I know the ranges are slightly different). I do the following to compare 2 DateTime values in my SP.
CREATE PROCEDURE [dbo].[spGetLikelyMatchedIndividuals_v1]
#ID BIGINT = NULL,
#DOB DATETIME = NULL, ...
WHERE ISNULL(CONVERT(CHAR(8),Ind.[DateOfBirth],112),'') = ISNULL(CONVERT(CHAR(8),#DOB,112),'')
This works fine in most cases but from some reason will fail with some Datetime. This is one datetime value that fails:
1925-07-04
Does anyone have anyidea why this may fail? Also what is the best way to compare two date values without the time component?
Seems like your date compare is correct. It may be other logic that is causing this issue. Perhaps you should paste in more of your stored procedure to find the likely problem.
Better yet, don't do any logic against the table as this will prevent your index from being used.
Let your front end app handle the ensuring that the #DOB variable is in the correct format.
If you're comparing dates on SQL-Server, investigate the DateDiff function.
You can compare two dates quite easily and specify the granularity, eg. to the nearest day or hour or minute or whatever.
In your example, one of your values is a datetime, so convert the other to that type using the Convert function.
You just want to compare the date component? You could compare
FLOOR(CAST(x.[SomeDate] as float)) = FLOOR(CAST(#SomeDate as float))
A lot less string work, and should do the job. Even better; create a 1-day range and use that...
DECLARE #from datetime, #to datetime
SET #from = CAST(FLOOR(CAST(#SomeDate as float)) as datetime)
SET #to = DATEADD(day, 1, #from)
...
WHERE x.[SomeDate] >= #from AND x.[SomeDate] < #to
String operation is expensive at times. Here is an example of selecting dates ignoring the time part without any casting:
Select dateadd(dd,0, datediff(dd,0, yourdatetimeval)) as date_column