DateTime.ParseExact method based on the use of details

  • 2020-05-10 18:46:29
  • OfStack

Parameters that
CultureInfo.CurrentCulture gets the region information for the current thread, including the DateTimeFormat date display format (date separator) and the NumberFormat currency.
Test cases:
1. When no separator is used in time:

string  temp = "18991230" ;
DateTime dateTemp = DateTime.ParseExact(temp, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None);

2. The use of a separator in time:

string  temp = "1899-12-30" ;
DateTime dateTemp = DateTime.ParseExact(temp, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
DateTime dateTemp = DateTime.ParseExact(temp, "yyyy/MM/dd", CultureInfo.CurrentCulture, DateTimeStyles.None);

All true, and why:
CultureInfo.CurrentCulture gets the DateTimeFormat property of the CultureInfo of the current thread as IFormatProvider, and then in the DateTimeParse.ParseByFormat method, when the/character of the format parameter is encountered, it compares whether the current character of the input date string is DateSeperator of the current DateTimeFormatInfo. If so, true is returned, that is, conversion is allowed, and if not, false is returned. In the current thread's regional information, the date separator is -, so the conversion succeeds.
It is best to use the following method if there is a separator:

string  temp = "1899-12-30" ;
DateTimeFormatInfo dtfi = new CultureInfo("zh-CN", false).DateTimeFormat; 
DateTime dateTemp =  DateTime.ParseExact(temp "yyyy-MM-dd", dtfi, DateTimeStyles.None) ;  // Use the current delimiter 


Related articles: