DateTime Property in ConfigurationElement

I want to put DateTime in a configuration file, however I want DateTime to be expressed in a certain way. I saw examples of using DateTime in a ConfigurationElement (like the example below). In the examples I saw, there is a date expressed in American format. I want to make sure that the date is clear to everyone no matter who they are, so I want to use it yyyy-MM-dd HH:mm:ssas a format.

How to do this when using a class derived from ConfigurationElement?

    class MyConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Time", IsRequired=true)]
        public DateTime Time
        {
            get
            {
                return (DateTime)this["Time"];
            }
            set
            {
                this["Time"] = value;
            }
        }
    }
+3
source share
3 answers

Are you sure? Afaik, the default style is XML, and you want this too (yyyy-mm-dd).

+3

, :

[ConfigurationProperty("Time", IsRequired=true)]
public DateTime Time
{
    get
    {
        return DateTime.ParseExact(
            this["Time"].ToString(),
            "yyyy-MM-dd HH:mm:ss",
            CultureInfo.InvariantCulture);
    }
    set
    {
        this["Time"] = value.ToString("yyyy-MM-dd HH:mm:ss");
    }
}
+4

I have a similar problem using the solution above. For me, the string "this [" Time "]. ToString ()" is like "2015/6/12 15:31:24", and the format parameter of the DateTime.ParseExact method is "yyyy-MM-dd HH: mm: ss" . Thus, this method cannot parse a string with a given format. Alternatively you can do, for example, below

if(this["Time"] is string)
{
    return DateTime.ParseExact(
        this["Time"].ToString(),
        "yyyy-MM-dd HH:mm:ss",
        CultureInfo.InvariantCulture);
}
else
{
    DateTime time = (DateTime)this["Time"];
    return DateTime.ParseExact(
        time.ToString("yyyy-MM-dd HH:mm:ss"),
        "yyyy-MM-dd HH:mm:ss",
        CultureInfo.InvariantCulture);
}
0
source

Source: https://habr.com/ru/post/1715365/


All Articles