-2

I use Persian Date (Iranian Date Format or Jalali Calendar) in my program.

and when i use this:

string A = "1396/2/30";
string Test = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(A));

I get the following error:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code. Additional information: String was not recognized as a valid DateTime.

Avestura
  • 1,438
  • 14
  • 24
  • 1
    Possible duplicate of [String was not recognized as a valid DateTime " format dd/MM/yyyy"](http://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy) – ASh May 20 '17 at 14:29
  • 1
    What is your `CurrentCulture` exactly? Be aware, you don't use _any_ calendar in your code. – Soner Gönül May 20 '17 at 14:31
  • As well as the accepted answer, I'd encourage you to consider using my Noda Time project (http://nodatime.org) which has what I'd consider to be rather clearer support for separate calendars than the BCL does. (For example, even after parsing, the `DateTime` will "forget" that it was parsed from the Persian calendar value...) – Jon Skeet May 21 '17 at 17:55

1 Answers1

3

Create a fa-IR CultureInfo and then try using DataTime.ParseExact() instead of Convert.ToDateTime().

Update

var persianCultureInfo = new CultureInfo("fa-IR");
persianCultureInfo.DateTimeFormat.Calendar = new PersianCalendar();
string dateString = "1396/02/30";
DateTime MyDateTime = DateTime.ParseExact(dateString, "yyyy/MM/dd", persianCultureInfo);
Avestura
  • 1,438
  • 14
  • 24
  • It did not work and again: "String was not recognized as a valid DateTime." "Damet Garm Vali Nashod :(" – Sh.Sobhani May 21 '17 at 15:29
  • 1
    Try changing `DataTimeFormat` calendar to a new instance of `PersianCalndar`. Updated answer will work without problem. – Avestura May 21 '17 at 17:13
  • New error: "Not a valid calendar for the given culture." – Sh.Sobhani May 21 '17 at 18:08
  • I tested this code and it worked fine. Are you sure you are referencing `System.Globalization.PersianCalendar` and you haven't imported any other calendar named `PersianCalendar` from other namespaces? – Avestura May 21 '17 at 18:17
  • It seems `PersianCalendar` can not be as the default calendar for a culture in .NET Framework 3.5 or any earlier versions of .NET. Change your target framework to .NET 4 or above to solve this issue. – Avestura May 21 '17 at 18:24
  • I use "ArashPersianCalendar" in WPF and my .NET Framework is 4.5!! – Sh.Sobhani May 21 '17 at 20:56