简体   繁体   中英

DateTime.TryParse Parses to wrong format

I am trying to parse a string (from a Textbox filled with english dateformat) to a DateTime using this code:

DateTime dt;
if (DateTime.TryParseExact(Text, DateTimeFormat, System.Threading.Thread.CurrentThread.CurrentCulture, DateTimeStyles.AssumeLocal, out dt))
{
    logger.Trace("LOCALE: {0} ", System.Threading.Thread.CurrentThread.CurrentCulture);
    logger.Trace("DateTimeFormat: {0} ", DateTimeFormat);
    logger.Trace("CurrentCulture ShortDatePattern: {0} ", System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
    logger.Trace("Text: {0} ", Text);
    logger.Trace("result of TryParse: {0} ", dt);
    return dt;
}

However the output in my logger is:

LOCALE: en-US 
DateTimeFormat ShortDatePattern: M/d/yyyy 
CurrentCulture ShortDatePattern: M/d/yyyy 
Text: 8/31/2012 
result of TryParse: 31-8-2012 0:00:00 

I am completly stuck why this is happening.

Using this code in a seperate console application DOES work:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string text = @"8/31/2012";
DateTime date;
string dateTimeFormat = @"M/d/yyyy";
bool parseOk = DateTime.TryParseExact(text, dateTimeFormat, Thread.CurrentThread.CurrentCulture, DateTimeStyles.AssumeLocal, out date);

extra info:

  • system: Windows 7 Ultimate EN
  • system language for non-UniCode: english
  • web.config system.web:

PROBLEM: The problem is I want the date to be in the format "M/d/yyyy" but instead it is parsed to "dd-mm-yyyy" which results in an invalid date

You have not specified an output string for the log entry, so it will use the default one (based on the current culture).

So, instead of:

logger.Trace("result of TryParse: {0} ", dt);

Use:

logger.Trace("result of TryParse: {0} ", dt.ToString("M/dd/yyyy"));

Or:

logger.Trace("result of TryParse: {0} ", dt.ToShortDateString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM