0

I want to convert a string to DateTime, but I get the following error.

String was not recognized as a valid DateTime.

int firstDayOfMonth = 1; int lastDayOfMonth = 31; int month = 3; int year = 2006; string sStartDate = string.Format("{0}/{1}/{2}", firstDayOfMonth, month, year); string eEndDate = string.Format("{0}/{1}/{2}", lastDayOfMonth, month, year); //This one works DateTime sDate = Convert.ToDateTime(startDate, CultureInfo.CurrentCulture.DateTimeFormat); //This one doesnt work DateTime eDate = Convert.ToDateTime(eEndDate, CultureInfo.CurrentCulture.DateTimeFormat); 

Then I tried this

DateTime date = new DateTime(year, month, lastDayOfYear); 

But then it gives me 3/1/2006 but I need it in dd/MM/yyyy

What can I do to convert the string to dd/MMyyyy?

2
  • It looks like your current culture is set to en-US but you are expecting it to be en-GB. Check your control panel settings. Commented Jan 27, 2015 at 8:21
  • What is your CurrentCulture? Commented Jan 27, 2015 at 8:22

3 Answers 3

8

Why don't you use the DateTime constructor instead of DateTime.Parse?

DateTime sDate = new DateTime(year, month, firstDayOfMonth); 

What can i do to convert the string to dd/MM/yyyy

You can conveerrt the DateTime to string using the proper format string and InvariantCulture to prevent that / gets replaced by the actual date separator of your culture.

string sStartDate = sDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); 
Sign up to request clarification or add additional context in comments.

2 Comments

Because then the order of month and day are swapped around. It gives MM/dd/yyyy and I want dd/MM/yyyy
@MikeBarnes: you are confusing a DateTime-value and how it is represented in the debugger (or wherever). A DateTime has just a value and no format. Note that i've edited my answer to show how to convert the DateTime to the desired string.
2

If you need to convert string to date with specific format you can use DateTime.ParseExact such as the following example

DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", CultureInfo.InvariantCulture); 

Comments

1

Convert.ToDateTime method uses your CurrentCulture settings by default.

Your sStartDate is 1/3/2006 but your eEndDate is 31/3/2006.

If this 1/3/2006 can be parsed successfully, that means your current culture has d/M/yyyy or M/d/yyyy (with your current culture date separator of course) as a standard date and time format but doesn't have dd/M/yyyy format.

You can find all standard date and time format of your CurrentCulture like;

foreach (var format in CultureInfo.CurrentCulture. DateTimeFormat. GetAllDateTimePatterns()) { Console.WriteLine(format); } 

Other than that, I agree with all what Tim Schmelter says.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.