Wednesday, December 22, 2021

c# - How to convert string into datetime with mask

DateTime dt;                      
bool b = DateTime.TryParseExact( "December 20, 2021", "MMMM d, yyyy", 
                                 new System.Globalization.CultureInfo("en-US"), 
                                 DateTimeStyles.None, out dt );
if ( b ) Console.WriteLine( dt.Year );
Output:
2021
if you have some problem with conversion, try reversal order at first for checking (=>compare if your string is same as output here):
Console.WriteLine( 
DateTime.Now.ToString( "MMMM d, yyyy", new System.Globalization.CultureInfo("en-US") ) );

No comments:

Post a Comment