Properly Format DateTime on XML Datetime - c#

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

Related

SQL Server Current_Timestamp Format

I'm learning SQL Server and have an update statement where the current date and time are inserted as follows:
UPDATE data_table
SET Date_Time_Cx = CURRENT_TIMESTAMP
When it is populated in the DB, it appears "Feb 22 2018 5:07PM". How do I get to populate with the format "YYYY-MM-DD hh:mm:ss"? I looked through the SQL Server documents and lots of posts and it seems like it should be populating in the desired way. Where did I go wrong? Thanks!
Then change the type of date_time_cx:
alter table data_table alter column date_time_cx datetime2;
Then it should go into the database using the proper types. You can format the value as you wish afterwards.
I'm not sure what this has to do with C#, but here's a solution for you using base SQL.
SELECT convert(varchar, getdate(), 121)
You can find all kinds of different date and time formats from the link below.
https://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/

Convert string to datetime value in LINQ

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

Error While Comparing Dates

I have an NVARCHAR column named Receivingdate. I want to compare its content with the current time, but when I call WHERE (Receivingdate < Getdate()), I get the following error:
The conversion of nvarchar to datetime resulted in an out of range value
I insert the data using the following call from C#:
DateTime.Now.AddDays(ces).ToString("dd/MM/yyyy");
I'm wondering what I'm doing wrong.
What you're doing wrong is storing dates in an NVARCHAR column. Please stop doing that. Fix your table and make that column using the DATE data type. The error is caused by garbage data getting into your table. Find those rows using:
SELECT Receivingdate FROM dbo.YourTable
WHERE ISDATE(ReceivingDate) = 0;
Now, you'll need to either correct or get rid of those before you fix the data type. Then:
ALTER TABLE dbo.YourTable
ALTER COLUMN ReceivingDate DATE;
Next, stop converting to a regional string format when inserting. Just insert the DateTime value from C# without calling .ToString() at all. There is absolutely no reason you should ever be converting to date to string and back again through any of this process, except at the point where you want to display it.
Your error is that you are trying to compare a string to a date. Dates are numbers. The only time to worry about format is when you are displaying them.
For what you have shown so far, change your c# code from
DateTime.Now.AddDays(ces).ToString("dd/MM/yyyy");
to
DateTime.Today;
and you should be ok.

C#+linq - Inserting DateTime value to the Db in the right format

I have a Db server with DateTime fields in the format of "yyyy-MM-dd mm:hh:ss"
I'm trying to use linq2sql to insert a DateTime member to a DateTime field in one of my tables.
When I do it in SQL I convert the DateTime as following:
"Insert into .... Convert(datetime, getdate(), 120) ..."
But when I try to submit the object from Linq the date time inserts in the wrong format.
Is there a way to define the format that will be inserted to the Db in Linq?
Or is it a DateTime object Issue?
You shouldn't be dealing with a string format when you pass dates and times to the database, any more than you would if you were passing a number. The database should be handling all this for you without any conversions. This is true whether you're using LINQ or within the SQL - almost any time you have to manually do string conversions between types at the database level, you should look for a better solution.
If you read the value back out of the database (as a DateTime again) does it have the right value? If not, in what way is it wrong?

SQL Server 2005 compare dates

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

Categories