0

I have the following xml file:

<Test>
    <Header>
       <Title>Test</Title>
       <Time>Wed Mar 21 14:37:04 2018</Time>
...

I can parse it and get the time:

public DateTime Time
{
    get { return _time; }
    private set { _time = value; }
}

foreach (XElement el in header.Elements()) {
    if (String.Compare(el.Name.ToString(), "Time", true) == 0) {
        string format = el.Value;
        _time = DateTime.ParseExact(format, "ddd MMM d H:m:s yyyy", CultureInfo.InvariantCulture);
        Console.WriteLine(_time);
    }
}

With the above solution, I can get the time but in the following format :

3/21/2018 2:56:40 PM

How can I get it in this format?

2018-03-21 14:56:40

Thanks in advance!

Peter B
  • 22,460
  • 5
  • 32
  • 69
Anton
  • 1
  • 1
  • 2

2 Answers2

2

Specifying a format doesn't make sense for a DateTime object. They have the months, days, years, minutes etc split up in their properties. See the documentation.

It doesn't make sense to ask for these to be in a certain order, unless you want to convert it to a string:

time.ToString("yyyy-MM-dd HH:mm:ss");

If you want to access certain parts of the datetime, you can use their properties directly:

time.Year;
time.Month;

etc.

JAD
  • 2,035
  • 4
  • 21
  • 35
  • @Anton what exactly are you *trying* to do though? As I said in my answer, as long as you are working with a `DateTime` object, the format is irrelevant. Once you use `ToString(format)` to specify a format, it is a string, and you lose `DateTime`-functionality. – JAD Mar 27 '18 at 11:09
0

Use DateTime.ToString(string format) to do that.

foreach (XElement el in header.Elements()) {
    if (String.Compare(el.Name.ToString(), "Time", true) == 0) {
        string format = el.Value;
        _time = DateTime.ParseExact(format, "ddd MMM d H:m:s yyyy", CultureInfo.InvariantCulture);
        Console.WriteLine(_time.ToString("yyyy-MM-dd HH:mm:ss"));
    }
}
Tanmay
  • 1,123
  • 1
  • 10
  • 20