c# - String format to convert datetime causes an error -
i try convert persiandate
standard date
.so persian date has these formats (it means user can enter these formats :
1392/1/1 1392/01/01 1392/01/1 1392/1/01
so write function convert persian date standard date :
public datetime convertpeersiantoenglish(string persiandate) { string[] formats = { "yyyy/mm/dd" }; datetime d1 = datetime.parseexact(persiandate, formats, cultureinfo.currentculture, datetimestyles.none); persiancalendar persian_date = new persiancalendar(); datetime dt = persian_date.todatetime(d1.year, d1.month, d1.day, 0, 0, 0, 0, 0); return dt; }
but these function can handle formats 1392/01/01
, of users enter other formats got error:
string not recognized valid datetime
best regards
you're specifying mm
, dd
in format, require 2 digits. specify "yyyy/m/d"
format - should handle both 1 , 2-digit day/month values. (you can specify multiple formats instead, in case don't need to. might want consider doing clear, m
, d
both handle 2 digit values leading 0 no problems.
note if you're specifying single format, don't need put in array. can use:
string format = "yyyy/m/d"; datetime d1 = datetime.parseexact(persiandate, format, cultureinfo.currentculture, datetimestyles.none);
however:
- i suspect want specify invariant culture, given don't want this value affected culture
- your current approach of converting date persian calendar not work.
currently you're implicitly validating date given in gregorian calendar, you're treating persian date. example, 1392/02/30 valid persian date, not valid gregorian date.
instead, should use culture uses persian calendar, , specify that culture in datetime.parseexact
call. don't need else afterwards.
you might alternatively want consider using noda time library - version 1.3 includes persian calendar should released in next day or two.
sample code using noda time:
var persian = calendarsystem.getpersiancalendar(); // pattern takes calendar system default value var sampledate = new localdate(1392, 1, 1, persian); var pattern = localdatepattern.createwithinvariantculture("yyyy/m/d") .withtemplatevalue(sampledate); var date = pattern.parse("1392/02/30").value; console.writeline(localdatepattern.isopattern.format(date));
Comments
Post a Comment