Save and load date and time

S-Soft 646 Reputation points

Hello all

I need to get date and time from a custom date time control and save it into registry, then load it back to the control.

DateTimeInput.Value.ToString will return: 11/18/2023 8:54:45 AM

Should save to registry as string?

Then what's the best method to parse the string back to DateTime?

Thanks :)

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,611 questions
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,659 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,496 Reputation points

    Strings are fine, but I'd specify the "round trip" O format to ToString. This ensures that it can be serialised/deserialised to/from a string without the time offset being misinterpreted:

    using System.Globalization;
    string now1 = DateTime.UtcNow.ToString("O");
    // .. Write "now1" to registry
    // Read "now1" from registry
    DateTime now2 = DateTime.Parse(now1, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

    You don't need to specify CultureInfo.InvariantCulture or DateTimeStyles.AdjustToUniversal to DateTime.Parse. These just ensure that the format of the string is assumed to be culture invariant & that the resulting DateTime instance has a Kind of Utc.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    Comments have been turned off. Learn more