Convert Specific Date String to any System Date Format Dynamically in C#

Suppose we have a date string input like "dd-MM-yyyy" now we want to convert into system date format dynamically means if we change the system date format MM-dd-yyyy then it must be converted into MM-dd-yyyy and if we change the system Date format yyyy-MM-dd so it must be converted into yyyy-MM-dd like that.

Actually whatever date string we are passed by default it is converted into system date format only. But the problem is what if we are passing string in the format dd-MM-yyyy and suppose the system date format is MM-dd-yyyy then it converts into MM-dd-yyyy but it take dd as MM and MM as dd that's the problem if we are passing 10-11-2015 (dd-MM-yyyy) so it's converting MM-dd-yyyy format like 10-11-2015 (MM-dd-yyyy) it's Completely wrong result. Take one example, if we are passing 27-11-2015 (dd-MM-yyyy) and system date format is what MM-dd-yyyy if you're trying to convert it gives you an exception ' Input string is not in a correct format'.

It's a great solution for converting specific date string to any system date format.

Note: Always remember whatever your month in input date string tries to replace with name of the month for example, if date string is 04/12/2015 so it must be like 04/December/2015.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Globalization;  
  6. namespace ConsoleApplication2  
  7. {  
  8.     class Program  
  9.     {  
  10.         public static DateTime GetDate(int dd, int MM, int yyyy)  
  11.         {  
  12.             //This will give you month name array dynamically  
  13.             string[] monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthGenitiveNames;  
  14.             //Date String dd-MM-yyyy(you can arrange in any formate of fixed formate also it givies you system date formate output)  
  15.             string DateString = dd + monthNames[MM - 1] + yyyy;  
  16.             //It Take a dynamically system date pattern  
  17.             string SystemDateFormate = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;  
  18.             //Converting DateString into system date formate   
  19.             string InputDate = Convert.ToDateTime(DateString).ToString(SystemDateFormate);  
  20.             //system date formate output  
  21.             DateTime ResultedDate = DateTime.Parse(InputDate);  
  22.             return ResultedDate;  
  23.         }  
  24.         static void Main(string[] args)  
  25.         {  
  26.             DateTime ConvertedDate = GetDate(04, 12, 2015);  
  27.             Console.WriteLine(ConvertedDate.Date);  
  28.             Console.ReadKey();  
  29.         }  
  30.     }  
  31. }

 

Ebook Download
View all
Learn
View all