Click here to Skip to main content
16,017,608 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
string input;
        DateTime db;
        Console.WriteLine("Enter Date in this Format(DD-MM-YYYY):");
        input = Console.ReadLine();


What I have tried:

I tried to enter the date in given format but it gives me format error how can i solve this?
Posted
Updated 27-Apr-16 22:33pm

1 solution

try this

C#
DateTime db;
      Console.WriteLine("Enter Date in this Format(DD-MM-YYYY):");
       string input = Console.ReadLine();
       string[] formats = { "d-M-yyyy", "d-MM-yyyy", "dd-M-yyyy", "dd-MM-yyyy" };
       db = DateTime.ParseExact(input, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);



for parsing with validation use this

C#
if (DateTime.TryParseExact(input, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out db))
           {
               DateTime date = db;
           }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900