Insert and display Date and Time from Database table in ASP.Net using C#

RichardSa
 
on Dec 03, 2022 04:44 AM
617 Views

I have an issue with time saved in the database. It does not give accurate time with my local time. If I insert data into the table with DateTime.Now, I thought it should get the time automatically in the local time and insert, so that when it displays, it will show exactly the time an event occurred.

Here is how I inserted the date and time with DataType: datetime

objCMD.Parameters.Add("@LastLogin", SqlDbType.DateTime, 100).Value = DateTime.Now;

OR

cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);

The displaying the date and time I use

timelbl.Text = Convert.ToDateTime(Session["LastLogin"]).ToString();

or when displaying in the Gridview I use

<asp:BoundField DataField="LastLogin" HeaderText="Date and Time" HeaderStyle-Font-Bold="false" />

Please what can I do to make the date and time work according to the real time local time and according to the machine time?

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
RichardSa
 
on Dec 03, 2022 07:05 AM
on Dec 03, 2022 07:22 AM

This is the value of LastLogin 12/3/2022 7:04:54 AM and my current time is 12/3/2022 3:04:54 PM

I am thinking of storing the datetime value in UTC and then convert the time to the time zone of my choosing.

like storing date and time in UTC, from this:

objCMD.Parameters.Add("@LastLogin", SqlDbType.DateTime, 100).Value = DateTime.Now;

 

cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);

Then I coud do something like this

objCMD.Parameters.Add("@LastLogin", SqlDbType.DateTime, 100).Value = DateTime.UtcNow;;

OR

cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Utc.Now);