简体   繁体   中英

Fixing Dates in C#

I am trying to create a textbox that will translate 1225 to 12/25/13. After having done a lot of research, I think "DateTime.TryParseExact" is what I need to use, but I can't get it to work. Here is my code:

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");
}

Any ideas how to fix this?

If it is possible to predict all possible formats, then you can try something like this

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();
}

对于您提供的示例,请考虑对代码进行以下更改...

string[] DateTimeFormats = new string[]{"MMdd"};

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).

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