Convert date in string to DateTime with same format

后端 未结 3 627
Happy的楠姐
Happy的楠姐 2021-01-20 21:02

I have a string that has a date stored in it.

String date = \"03-05-2013 00:00:00\";

I parsed it to Datetime as follows:

Da         


        
3条回答
  •  一个人的身影
    2021-01-20 21:52

    I need to keep the original formatting.

    Then you need to apply the same pattern again when you call ToString:

    string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
                                      CultureInfo.InvariantCulture);
    

    (Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)

    Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".

    A DateTime value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.

提交回复
热议问题