简体   繁体   中英

DateTime.TryParseExact returning false

I am trying to get the DateTime format using DateTime.TryParseExact

DateTime logDate;

DateTime.TryParseExact(
    string.Format("{0}/{1}/{2}", day, month, ddlYear.SelectedValue),
    "dd/MM/yyyy",
    null,
    System.Globalization.DateTimeStyles.None,
    out logDate);

it is returning false . am i missing something?

eg day=01, month=02, year= 2013

It's hard to say exactly what's the problem, but you should try specifying DateTimeFormatInfo.InvariantInfo as DateTime.TryParseExact parameter:

DateTime.TryParseExact(
    "20/12/2013",
    "dd/MM/yyyy",
    System.Globalization.DateTimeFormatInfo.InvariantInfo,
    System.Globalization.DateTimeStyles.None,
    out logDate);

That's because / has special meaning within your pattern string:

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

from Custom Date and Time Format Strings: The "/" Custom Format Specifier

There is a chance that the culture you're running your application in has date separator different then / itself.

I guess the day and month are of type int and hence the resultant is not recognized, so better off using d/M/yyyy format.

DateTime.TryParseExact(
    string.Format("{0}/{1}/{2}", day, month, ddlYear.SelectedValue),
    "d/M/yyyy",
    null,
    System.Globalization.DateTimeStyles.None,
    out logDate);

your string should come out as "1/2/2013"

The format of the string representation must match the specified format exactly.

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