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

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
  • Your second argument must match the string with the date to parse, it's obviously not the case here. Add the missing part. – AFract Jul 02 '18 at 06:40
  • Possible duplicate of [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Mohammad Javad Noori Jul 02 '18 at 06:40

2 Answers2

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!

Karan
  • 12,059
  • 3
  • 24
  • 40
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!

aloisdg
  • 22,270
  • 6
  • 85
  • 105