Converting a String to DateTime

后端 未结 17 2581
南方客
南方客 2020-11-21 06:12

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?

17条回答
  •  名媛妹妹
    2020-11-21 06:34

    You have basically two options for this. DateTime.Parse() and DateTime.ParseExact().

    The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.

    ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.

    You can parse user input like this:

    DateTime enteredDate = DateTime.Parse(enteredString);
    

    If you have a specific format for the string, you should use the other method:

    DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
    

    "d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.

提交回复
热议问题