Date time issue

Peter_1985 2,526 Reputation points
2023-06-28T04:53:47.47+00:00
Hi,
I have the code like
                        to_dt_val = tb_valid_to.Text.Trim() + " 12:00:00 AM";
                        cmd4.Parameters.Add("@dt0", SqlDbType.DateTime).Value = DateTime.ParseExact(to_dt_val, to_dt_format, CultureInfo.InvariantCulture);

it is having the time (on the day) shown on the page. But the time part disappears when I put the cursor on the field and leave the field. How to resolve it?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,267 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Francesco Ciurria 0 Reputation points
    2023-06-29T10:38:10.89+00:00

    It seems like you're encountering an issue where the time part disappears when you interact with the field. This could be due to the way the field is handling the date value.

    One possible solution is to modify the code to explicitly set the time part of the DateTime value to ensure it remains consistent. Here's an updated version of your code:

    to_dt_val = tb_valid_to.Text.Trim() + " 12:00:00 AM";
    DateTime toDateTime = DateTime.ParseExact(to_dt_val, to_dt_format, CultureInfo.InvariantCulture);
    toDateTime = toDateTime.Date + new TimeSpan(0, 0, 0); // Set the time to midnight (00:00:00)
    cmd4.Parameters.Add("@dt0", SqlDbType.DateTime).Value = toDateTime;
    

    In the updated code, we extract the date from the toDateTime value using the .Date property and then add a TimeSpan of zero hours, zero minutes, and zero seconds to set the time part to midnight (00:00:00).

    By doing this, you ensure that the time component of the DateTime value remains unchanged, even if the field behavior removes it temporarily.