2

I am getting issue while converting string to DateTime.

The value I am receiving as "08-26-2015 10:14:57.898Z".

I am trying to convert the above string to DateTime.

My Code:

DateTime.ParseExact(element.Value,"MM/dd/yyyy HH:mm:ss",CultureInfo.CurrentCulture);

Exception: String was not recognized as a valid DateTime.

3
  • What's your current culture? Commented Aug 27, 2015 at 14:17
  • @juharr -Even i tried with CultureInfo.InvariantCulture,i am getting same exception.My current culture ="en-US" Commented Aug 27, 2015 at 14:20
  • Then the problem is the date separator. For US and Invaiant it's a slash / and not a dash -. As others have mentioned you might want to use DateTime.Parse or Convert.ToDateTime instead or specify that you want dashes as the separator in the format. Also you need to specify the milliseconds and the Z at the end. Commented Aug 27, 2015 at 14:22

4 Answers 4

2

You have string with different format than you trying for conversion.

Try this

var input = "08-26-2015 10:14:57.898Z";
var date = DateTime.ParseExact(input, "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

2 Comments

Better to use CultureInfo.InvariantCulture, in case the current culture is using a time separator other than colon (:)
@Joe Thanks for suggestion :)
2

You can use:

DateTime dt = DateTime.ParseExact("08-26-2015 10:14:57.898Z", "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);

If you use CultureInfo.CurrentCulture(or null) the slash / has a special meaning. It is replaced with the current culture's date separator. Since that is not - but / in US you get an exception. Read

Comments

0

Have you tried Convert.ToDateTime ? I just tried with your string and it works fine :

var s = "08-26-2015 10:14:57.898Z";
var date = Convert.ToDateTime(s);

2 Comments

--Still facing issue,tried with X-TECh solution and it worked
Happy to know you found the solution :)
0
String s = "08-26-2015 10:14:57.898Z";
DateTime date;
DateTime.TryParse (s, out date);

Now date variable contains DateTime value you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.