DateTime property in a ConfigurationElement
Asked Answered
O

3

5

I'm wanting to put a DateTime in to the config file, however, I want the DateTime expressed in a specific way. I've seen examples of using a DateTime in a ConfigurationElement (like the example below). The examples I've seen all have the date expressed in American format. I want to ensure that date is understandable by all regardless of who they are so I want to use yyyy-MM-dd HH:mm:ss as the format.

How do I do that 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;
            }
        }
    }
Ochre answered 17/8, 2009 at 21:16 Comment(0)
J
3

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

Judicator answered 17/8, 2009 at 21:26 Comment(1)
Doh! Yes, it works without modification. That's what I get for trying to read up on stuff and not actually trying it out to see for myself. Dr. Feynman will be spinning in his grave.Ochre
S
4

I guess you can use the following:

[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");
    }
}
Shaveling answered 17/8, 2009 at 21:31 Comment(0)
J
3

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

Judicator answered 17/8, 2009 at 21:26 Comment(1)
Doh! Yes, it works without modification. That's what I get for trying to read up on stuff and not actually trying it out to see for myself. Dr. Feynman will be spinning in his grave.Ochre
K
0

I have similar problem using above solution. For me, the string of "this["Time"].ToString()" is like "2015/6/12 15:31:24", while format parameter of method DateTime.ParseExact is "yyyy-MM-dd HH:mm:ss". So this method can't parse the string with given format. Alternatively, you can do like 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);
}
Knurly answered 13/6, 2015 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.