0

I am facing an issue while assign value to DateTime stdt please find below my code logic

startdate="06/20/2016 12:30" //format (MM/dd/yyyy HH:mm)

DateTime stdt = Convert.ToDateTime(startdate);

also, I had tried with below code but didn't work.

DateTime stdt = DateTime.ParseExact(startdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

5
  • 3
    Try DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture); . With ParseExact you have to give the exact format Commented Jun 3, 2016 at 7:04
  • I had tried with as your solution but I am getting this error 'The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.' Commented Jun 3, 2016 at 7:09
  • @AKS : are you sure the string you parse is exactly the one on your example, with no hidden characters or other problems ? The Pikoh's answer seems ok for me. Commented Jun 3, 2016 at 7:15
  • @aks note 'MM' before ´dd´ Commented Jun 3, 2016 at 7:16
  • 1
    sorry @Pikoh your solution is working I just forgot to change "MM/dd/yyyy HH:mm" thanks Commented Jun 3, 2016 at 7:17

3 Answers 3

4

According your date, you should use :

DateTime stdt = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture); 

to match each part of your date.

Please see here : https://msdn.microsoft.com/en-US/library/w2sa9yss%28v=vs.110%29.aspx for method usage

And https://msdn.microsoft.com/en-US/library/az4se3k1(v=vs.110).aspx for date patterns

Sign up to request clarification or add additional context in comments.

Comments

1

I think this will work:

DateTime stdt = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture); 

you have to put the formatting of the string that you pass to the method.

Comments

0

If you don't want to pass the format, you can use the culture:

 var date = DateTime.Parse("06/20/2016 12:30", new CultureInfo("en-US")); 

2 Comments

I think this will fail : "MM/dd" is not the typical usage for french dates, day is before month in french, so this will fail. If dateformat is always the same, it seems better to me to use explicit pattern.
Yes that's true I only wanted to give an idea of how to proceed (-; Should work with "new CultureInfo("en-US")"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.