C# DateTime Default Value Issue 01/01/0001 00:00:00 - c#

I am having trouble inserting a DateTime into a database with the following error:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
I am aware that the SQL date must be between 1/1/1753 12:00:00 AM and 12/31/9999, however my date seems to remain at the 01/01/0001 00:00:00.
I have the following date defined in a web service method:
[DataMember]
public DateTime RecordTimeStamp { get; set; }
This is used in the following code to add into database
sqlComm.Parameters.Add("#RecordTimeStamp", SqlDbType.DateTime).Value = pCustomer.RecordTimeStamp;
This code takes its value from an aspx page with code
DateTime now = DateTime.Now;
pCustomer.RecordTimeStamp = now;
I am trying to get this to insert the current date into the database, but it doesn't seem to change from the default.

Try to change the property
from:
[DataMember]
public DateTime RecordTimeStamp { get; set; }
to:
[DataMember]
public DateTime? RecordTimeStamp { get; set; }
Hopefully this will fix the issue. What happens is DateTime is NOT NULL data type and it enforces to put a default value there (01/01/0001) to make sure that non-null date will be submitted. I don't know why it does not accept altered value and throws out an "out of range" exception. That is something you might want to investigate further.

Related

Bind date without time conversion issue between DateTime and DateTimeOffset

I have an API and the API take input in body as below,
{"CreatedDate" :"2022-11-01", "CreatedDate1" :"2022-11-01"}
The API have a Dto which have 2 properties to bind these values,
public DateTime CreatedDate { get; set; }
public DateTimeOffset CreatedDate1 { get; set; }
One is DateTime and another DateTimeOffet. When I run the API I see the below results,
dto.CreatedDate.ToString()
"11/1/2022 12:00:00 AM"
dto.CreatedDate.ToLocalTime().ToString()
"11/1/2022 4:00:00 AM"
dto.CreatedDate.ToUniversalTime().ToString()
"10/31/2022 8:00:00 PM"
dto.CreatedDate1.ToString()
"11/1/2022 12:00:00 AM +04:00"
dto.CreatedDate1.ToLocalTime().ToString()
"11/1/2022 12:00:00 AM +04:00"
dto.CreatedDate1.ToUniversalTime().ToString()
"10/31/2022 8:00:00 PM +00:00"
I am confused by CreatedDate1.ToString() and CreatedDate1.ToLocalTime().ToString() are same but CreatedDate.ToString() and CreatedDate.ToLocalTime().ToString() are not.
Does this intended behavior of DateTime?

Best way to Pass Typescript Date property as a parameter to a Web Api 2.0 method

I have a date picker in html which is bound to a Date property of an employee.
ex: i have selected the date as "Thu Feb 22 2018 00:00:00 GMT+0530 (India Standard Time)".this is the value i get when i log in console.
But when i tried to debug in C# the value is changed.
{21-02-2018 18:30:00}
How to handle or work with the typescript date object when passing it to a API method and displaying it back
My typescript Model
export class Visitor {
public id: number;
public firstname: string;
public lastname: string;
public dob: Date;
public genderId: number;
public age: number;
}
and C# model
public class Visitor
{
public int Id { get; set; }
public string Lastname { get; set; }
public string Firstname { get; set; }
public int Age { get; set; }
public DateTime DOB { get; set; }
}
As long as you are passing a valid Date object you should be fine.
Your problem probably lies in your Culture settings in .NET side.
Can you please try doing this in your controller action:
var culture = new CultureInfo("gu-IN");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
Since you provide no code, this is merely a guess.
When you are printing in console, browser is printing the date in local timezone which is India in your case. When you are retrieving the value on server, C# is treating date in UTC. That is why you see a difference of 5.30 hours. India time is UTC + 5.30 Hours.
If you are storing the date value in UTC format on server side then convert the value of date object from client side to UTC using the libraries such as momentjs.
While retrieving the value from server, send the UTC value from server and convert it to local time zone using libraries such as momentjs. I think this strategy will work.

store only date in database not time portion C#

I have a test class and an ExecutionDate property which stores only date but when we use [DataType(DataType.Date)] that also stores the time portion in database but I want only date portion.
public class Test
{
[Key]
public int Id { get; set; }
[DataType(DataType.Date)]
public DateTime ExecutionDate { get; set; }
}
Is any way to store only date on time portion in db using Entity Framework? Please help me....
I have added snapshot when use [DataType(DataType.Date)] that stores time portion 00:00 I want remove that
I think you are trying to specify database column type. You could use data annotations as described in this article.
Here is an example :
[Table("People")]
public class Person
{
public int Id { get; set; }
[Column(TypeName = "varchar")]
public string Name { get; set; }
[Column(TypeName="date")]
public DateTime DOB { get; set; }
}
By default, string is translated to nvarchar, we have changed that here. Also Datetime (this is what you asked I suppose) which by default maps to datatime in sql server, is changed to date which stores only the date portion and not the time portion of a DateTime value.
On EF core one may add override OnModelCreating in DbContext class.
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Test>().
Property(p => p.ExecutionDate)
.HasColumnType("date");
}
As David said above, once you bring that data into the application it will be a DateTime with the timestamp added onto the date. This would be the same result too if you stored the date as a string and used Convert to change to a DateTime for any manipulation:
string date = "2015-11-17";
var dateTime = Convert.ToDateTime(date);
Unless you want to manipulate strings in your application to avoid the timestamp, you can only work with DateTime. For display purposes though, you can always format the date and remove the timestamp:
var dateTime = DateTime.Now;
var formatDate = dateTime.ToString("yyyy-MM-dd");
In .NET 6 now you have new special type - DateOnly
More info here:
https://github.com/dotnet/efcore/issues/24507
https://www.stevejgordon.co.uk/using-dateonly-and-timeonly-in-dotnet-6
Change datatype on the database from Datetime to Date type
Is it really an issue for you anyway? You may want time in there at some point,
Change DateTime to nvarchar(10) in database
if u use DateTime in database 00.00.00 will be automatically assigned by database
string date = DateTime.Today.ToShortDateString();

how to format a date inside a collection of objects using linq in c#

I have a list of objects in my collection and need to format the date on an object date property (NoteDate) to show dates in the format like "dd'/'MM'/'yyyy HH:mm:ss" whereas in database the format of the date is like '2015-02-19 00:00:00.000'. Below is my object
public class Note
{
public int Id { get; set; }
public string NoteText { get; set; }
public DateTime? NoteDate { get; set; }
}
and I populate the collection as below
var notesList= _uow.Find<Note>(n => n.FK == leadId).ToList();
how can we write the query to get the desired date format?
thanks
You are, properly, storing the date in a DateTime? object. DateTime is simply a storage mechanism.
What you are really interested in is how to display the DateTime in some UI.
So here's the steps your Date/Time is going to take:
Get returned as query content from the database
Get stored in the DateTime property
Be shown to the user
To format a value from a DateTime object there are several options - check out the methods on the DateTime class.
Your dates will be represented as a DateTime instance .. how .NET decides to represent dates.
When you're displaying them to your user/using them for display somewhere, you can simply format them at that point. For example:
var notesList = _uow.Find<Note>(n => n.FK == leadId).ToList();
var thirdNoteDateString = notesList[2].NoteDate.ToString("dd MM yyyy");
Or, perhaps in a Razor view (if this was an MVC application):
#foreach (var n in Model.Notes) {
<p>#n.NoteDate.ToString("dd MM yyyy")</p>
}
Hopefully that shows the difference. How the date is presented is up to you when you decide to present it.
you should not modify the content of your buisness object just for a Show purpose,
You should use a converter or a StringFormat like :
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
see this question for more info

Date format issue with DatePicker asp.net mvc

I have a problem with datepicker format, it sets the date to MM-dd-yyyy. First, my model was set to following date format dd-MM-yyyy, I've changed it to MM-dd-yyyy in my model but nothing happen, the jqueryval script throw an error it wants the dd-MM-yyyy format.
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? dateOut_cash
{
get;
set;
}
So how can I set it to have everything working well ?

Categories