1

How to convert string: "14/07/2018 14:00:00 ق.ظ" to datetime ?

I am using Convert.ToDateTime() and

DateTime dt = DateTime.ParseExact("14/07/2018 14:00:00 ق.ظ", 
    "dd/MM/yyyy", CultureInfo.InvariantCulture);

I got an exception

String was not recognized as a valid DateTime

2
  • Your second argument must match the string with the date to parse, it's obviously not the case here. Add the missing part. Commented Jul 2, 2018 at 6:40
  • Possible duplicate of Converting a String to DateTime Commented Jul 2, 2018 at 6:40

2 Answers 2

4

In DateTime.ParseExact second parameter format need to match exactly as per string you are passing.

DateTime dt = DateTime.ParseExact("14/07/2018 14:00:00 ق.ظ", "dd/MM/yyyy HH:mm:ss ق.ظ", CultureInfo.InvariantCulture);

If you want only date part then add .Date at the end as below.

DateTime dt = DateTime.ParseExact("14/07/2018 14:00:00 ق.ظ", "dd/MM/yyyy HH:mm:ss ق.ظ", CultureInfo.InvariantCulture).Date;

Try it online!

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

2 Comments

I think it is a nice solution if you want everything
If you want only date then just add .Date at the end.
2

A quick and dirty solution would be to clean the date ahead. Something like this would work:

var date = "14/07/2018 14:00:00 ق.ظ";
DateTime dt=DateTime.ParseExact(date.Remove(date.IndexOf(" ")), "dd/MM/yyyy", CultureInfo.InvariantCulture);

Console.WriteLine(dt.Day);
Console.WriteLine(dt.Month);
Console.WriteLine(dt.Year);

Output

14
7
2018

Try it online!

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.