0

我正在尝试创建一个将 1225 转换为 12/25/13 的文本框。在做了很多研究之后,我认为“DateTime.TryParseExact”是我需要使用的,但我无法让它工作。这是我的代码:

CultureInfo provider = CultureInfo.InvariantCulture;

DateTime dateValue;

string[] DateTimeFormats = new string[]{
    "MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
    "M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
    "MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
    "MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
    "MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
    "MMddyy HHmm","MMddyy HHmmss",
    "MMddyyyy HHmm","MMddyyyy HHmmss",
    "yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss"};

if (DateTime.TryParseExact(TheTextBox.Text, DateTimeFormats, provider, DateTimeStyles.None, out dateValue))
{
    TheTextBox.Text = dateValue.ToString("d MMMM yyyy");
}

任何想法如何解决这一问题?

4

3 回答 3

1

如果可以预测所有可能的格式,那么您可以尝试这样的事情

static void Main(string[] args)
{
    CultureInfo enUS = new CultureInfo("en-US");
    string dateString;
    DateTime dateValue;


    dateString = "0501";

    var dateFormats = new String[] {"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
    "M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
    "MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
    "MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
    "MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
    "MMddyy HHmm","MMddyy HHmmss",
    "MMddyyyy HHmm","MMddyyyy HHmmss",
    "yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss", "MMdd"};

    bool matchFound = false;
    foreach (var dateFormat in dateFormats)
    {
        if (DateTime.TryParseExact(dateString, dateFormat, enUS, DateTimeStyles.None, out dateValue))
        {
            matchFound = true;
            Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue.ToString("dd MM yyyy"), dateValue.Kind);
        }
    }
    if (!matchFound)
        Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

    Console.ReadKey();
}
于 2013-11-08T20:59:38.907 回答
0

For the example you provided consider the following change to your code...

string[] DateTimeFormats = new string[]{"MMdd"};
于 2013-11-08T20:48:32.947 回答
0

You can use DateTime.ParseExact to translate your string into a DateTime:
The text of the textBox1 is 1225:

DateTime date = DateTime.ParseExact(textBox1.Text,"MMdd",CultureInfo.InvariantCulture);
string yourDate = date.ToString("MM/dd/yy"));
//yourDate is 12/25/13

Note: This will always return the date with the current year (here: 2013).

于 2013-11-08T20:51:12.117 回答