Blazor C# date shows as 1/1/0001 12:00:00Am - c#

I'm completely fresh to Blazor and have just dived into a project.
I'm using ORM to pull up data from a database. For some reason when I return the data, it is being shown as 1/1/0001 12:00:00Am
This is how I grab the data from DB
string sql = "Select top Value1, Value2, Value_DateTime from DBO.T_1";
return _db.LoadData<Model1, dynamic>(sql, new { });
And this is how I try to populate a table with a value, in .Razor page
<td>#Value.Value_DateTime</td>
All other data appears correctly. When I run the query in SSMS, it shoes correct dates.
EDIT:
Task<List<T>> LoadData<T, U>(string sql, U parameters);

The issue might be incompatibility between SQL DateTime datatype and C# System.DateTime struct. There is an alternative version: System.Data.SqlTypes.SqlDateTime struct - switching to that struct in your Model should™ fix your problem.
Here's the docs link: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqltypes.sqldatetime?view=dotnet-plat-ext-3.1
Relevant excerpt:
...The SqlDateTime structure has a different underlying data structure from its corresponding .NET Framework type, DateTime...

Blazor C# date shows as 1/1/0001 12:00:00Am
You are showing a DateTime that has not been initialized. Somewhere in your code you are simply not moving the data from the database into the field that you then show out. Sadly, your code is so non-standard I will not debug it - especially because of unneeded use of dynamics - but somewhere there you make a mistake.

Related

Postgres and c# - DateTime with timezone confusion

Hopefully not a repost of another... a rather simple question, but I think I'm fundamentally confused about how dates/times with timezones are handled between Postgres and c#.
Simple situation, at one point in the program I call DateTime.Now and save to a variable 'now'. This is inserted into a Postgres DB.
cmd.Parameters.AddWithValue("createdat", now);
Great. The column that this is inserted into is of type "timestamp with time zone". When I view the result from something like DataGrip or DBeaver the raw data is exactly what I want (I think).
2021-03-09 15:07:51
Later on I query this table in a rather simple way.
SELECT createdat FROM mytable WHERE mycondition;
I cast it as a c# DateTime type and populate a class with it.
while (reader.Read())
{
myClass.createdAt = (DateTime) reader["createdat"];
}
However, the value is populated as the following:
3/9/2021 10:07:51 AM
Something is not working here. First, if the column in the DB is of timestamp with time zone, where is the time zone information? Second, if the time zone is working, since it is being both populated and queried from the same computer, why is there a discrepancy? Third, and the pressing issue, how do I solve this? Must I explicitly define the time zone? I'm confused as to why it is returning different data... Hopefully, someone can help me out.
I think Dbeaver is changing the time zone, but the data inserted is the same you get on c#. Try to check directly on the server using commandline because maybe dbeaver is changing it to diplay on your pc

DateTime2 conversion randomly removes space between date and time

I have a small console application which is to import a CSV file into a database. It is in .NET CORE 3.1. The CSV file gets imported without any issues. The issue arises with trying to save the data to the table. The error being received is "String or binary data would be truncated. The statement has been terminated." This is received during the context.SaveChanges() call. To determine exactly what the error is, loaded up Profiler to see the offending statement. The offending piece of code was related to a field that holds a date and time. To start from the beginning and lead up to the issue.
The imported data is in a column and is represented as follows:
"20200404121655500"
"20200404121755500"
The import model property is defined as follows:
public string Date_And_Time { get; set; }
The data model property is defined as follows:
[Column(TypeName = "DATETIME2(7)")]
public DateTime? Date_And_Time { get; set; }
The conversion used to get the imported string to the data model field is as follows:
if (DateTime.TryParseExact(Date_And_Time.Trim()
.PadRight(21, '0')
.Substring(0, 21), "yyyyMMddHHmmssFFFFFFF", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime newDateTime))
{ model.Date_And_Time = newDateTime; }
else { model.Date_And_Time = null; }
While debugging when the 2 different dates are processed then are set in the model.Date_And_Time as expected. The object expands producing all the correct information (year, day, hour, etc.). Prior to executing SaveChanges, inspecting the objects shows they both have correct DateTime objects. However upon executing that command throws the above SQL exception. When inspecting the merge command created by EF the dates are differently formatted. They are as follows:
'2020-04-0412:16:55.5000000' and '2020-04-04 12:17:55.5000000'
The first does not have a space between the date and time where as the second has a space. The first is what is causing the exception. When doing the SaveChanges there are on average 20 records being saved and some have the space and some do not there is no pattern that I can find. I have tried using the exact same date time and that also has some with and some without space.
After some trial and errors I switched from DateTime to DateTimeOffset. This was done on the property of the data model propriety, the type attribute of the same property and the TryParseException. No other changes and it ran with no exceptions. Needed to do another migration due to the change in attribute causing the table field tire change.
The only 3rd party package used was to import the CSV for and that went successfully.
The parametrized merge statement was seen in the profiler sorry I didn't City it better finding the answer.
I have no idea why the model with a C# data type of DateTime would produce a string although the parameter itself was designated as DateTime2 the value being passed in was in string format.
I don't understand what the difference is between the 2 data types and how they are handled that would cause this issue. I appreciate the comments and attempting to help.

Datetime format is 'mm-dd-yyyy' when getting while using SqlDataAdapter but if I run the same query in ms sql then its 'yyyy-mm-dd'

I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.

sqldate time overflow in ASP.NET using VB.NET

I've been through a tough day facing this problem. In ent object, I have DiinputTanggal property as Date. In database, I have DiinputTanggal column as DateTime. When I try to insert the ent object into the database, I got the following error shown in the screenshot below. But when I debug, the property DiinputTanggal in ent object seems perfectly fine and nicely formatted. I have no idea where is my mistake.
Looking at your screenshot, it is probably the TaggalAktif property which is causing the overflow. .Net DateTimes default to DateTime.MinValue which cannot be represented in SQL DateTime.
You have several options
Initialize the DateTime to a value supported by Sql DateTime (in the range indicated by the error)
Change the DateTime to be nullable in both the class and database, (and ensure the property is initialized to null).
Use another Sql DataType to store the data e.g. DateTime2 or just Date if time isn't needed.

How can i set sql date time with entity framework c#.net

I am very new to entity framework. Nice concept and fast as well.
Working in c#.net right now. I have stucked here where datetime comes in picture.
I mean....
lets assume i have user table in DB where CreatedDate fields is there in with datetime datatype in sql db.
My entity framework works like this...
when i need to add object to db, i simply pass objUser.createdDate = DateTime.now.
How ever I want to change the concept for some requirement changes.
I need to store sql server DateTime() for createdDate field in table.
How can i do that???
any idea...please help.
follwoing is a just sample code of my project.
objCustomer.RegisterDate = DateTime.Now;
objCustRepository.AddCustomer(objCustomer);
I want to remove this DateTime.Now line and maintain through sql....
if you can store the value from stored procedure instead of your business logic then you can try it by following.
to store SQL Datetime value then you can also use GETDATE() function in SQL.
or
you can define RegisterDate default value = GETDATE()
It sounds like you are trying to target the specific timezone associated with your sql server, if I am not mistaken?
If so why not use DateTimeOffset.Now via your c# when setting the date.
See this blog post here about the type.
A DateTimeOffset represents a specific point in time, so you can use it to convert to any timezone representation you may need on your UI.
Be aware though that it is only supported on SQL Server 2008 and greater, if I remember correctly. :)

Categories

Resources