Convert a string to a date in .net

后端 未结 6 1558
忘了有多久
忘了有多久 2020-12-10 15:21

I\'m reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest

6条回答
  •  伪装坚强ぢ
    2020-12-10 16:06

    string[] formats = {"yyyyMMdd", "MM/dd/yy"};
    var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
    

    or

    DateTime result;
    string[] formats = {"yyyyMMdd", "MM/dd/yy"};
    DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
    

    More info in the MSDN documentation on ParseExact and TryParseExact.

提交回复
热议问题