开发者

Convert String to Date in .NET if my incoming date format is in YYYYMMDD

开发者 https://www.devze.com 2022-12-19 03:46 出处:网络
What is the best way to convert string to date in C# if my incoming date format is in YYYYMMDD开发者_Python百科

What is the best way to convert string to date in C# if my incoming date format is in YYYYMMDD开发者_Python百科

Ex: 20001106


Use DateTime.ParseExact(). Something like:

   string date = "20100102";
   DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);


 DateTime.TryParseExact(myDateString, "yyyyMMdd", 
                         CultureInfo.InvariantCulture, 
                         DateTimeStyles.None, out myDateVar )


Check DateTime.ParseExact or DateTime.TryParseExact.


use DateTime.TryParseExact with a pattern string of "yyyyMMdd" if you are on .NET 2.0 or better.

If you are stuck with .NET 1.1 use DateTime.ParseExact

see Standard DateTime Format Strings for the rules for making pattern strings.


DateTime yourDateTime = DateTime.ParseExact(yourString, "yyyyMMdd", null);


Using TryParseExact is generally nicer than ParseExact as it won't throw an exception if the conversion fails. Instead it returns true if it's successful, false if it's not:

DateTime dt;
if (DateTime.TryParseExact("20100202", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
   Console.WriteLine(dt.ToString());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消