Write a C# Sharp program to convert the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style

  • برمجة سي شارب
  • برمجة

Write a C# Sharp program to convert the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 

Expected Output:

Unable to convert '8/1/2016 6:32 PM' to a date.                        
Unable to convert '08/01/2016 6:32:05 PM' to a date.                   
Converted '8/1/2016 6:32:00' to 8/1/2016 6:32:00 AM.                   
Converted '08/01/2016 06:32' to 8/1/2016 6:32:00 AM.                   
Unable to convert '08/01/2016 06:32:00 PM' to a date.                  
Converted '08/01/2016 06:32:00' to 8/1/2016 6:32:00 AM. 

الأجوبة

using System;
using System.Globalization;

public class Example21
{
   public static void Main()
   {
      string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                         "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                         "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                         "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                         "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
      string[] dateStrings = {"8/1/2016 6:32 PM", "08/01/2016 6:32:05 PM", 
                              "8/1/2016 6:32:00", "08/01/2016 06:32", 
                              "08/01/2016 06:32:00 PM", "08/01/2016 06:32:00"}; 
      DateTime dateValue;

      foreach (string dateString in dateStrings)
      {
         if (DateTime.TryParseExact(dateString, formats, 
                                    new CultureInfo("zh-CN"), 
                                    DateTimeStyles.None, 
                                    out dateValue))
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
         else
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
      }
   }
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...