Unable to convert string to date

  • Thread starter Abhishek Srivastava
  • Start date
A

Abhishek Srivastava

Hello All,

I wrote the following program.

using System;
using System.Globalization;

public class ShortDateTest
{
public static void Main(string[] args)
{
string date = @"26/04/1974";
DateTimeFormatInfo dtInfo = new DateTimeFormatInfo();
dtInfo.ShortDatePattern = @"dd/mm/yyyy";
DateTime birthDay = Convert.ToDateTime(date, dtInfo);
Console.WriteLine(birthDay.ToString());
}
}

But it throws an exception saying

Unhandled Exception: System.FormatException: Could not determine the
order of ye
ar, month, and date from dd/mm/yyyy.
at System.DateTimeParse.GetYearMonthDayOrder(String datePattern,
DateTimeForm
atInfo dtfi)
at System.DateTimeParse.GetDayOfNNY(DateTimeResult result,
DateTimeRawInfo ra
w, DateTimeFormatInfo dtfi)
at System.DateTimeParse.ProcessTerminaltState(Int32 dps,
DateTimeResult resul
t, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi,
DateTimeStyl

Why I am not able to parse this date? I have used this same methodology
successfully to parse dates of pattern dd-MMM-yy. So why doesn't it work
for dd/mm/yyyy?

thanks for your help in advance.

regards,
Abhishek.
 
G

Guest

I think you should change the

dtInfo.ShortDatePattern = @"dd/mm/yyyy"; to

dtInfo.ShortDatePattern = @"dd/MM/yyyy";

the Month character must be capitalized.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top