I have datetime in one simple textbox. The format of the textbox's value can be anything like DD/MM/YYYY or MM/DD/YYYY. I want to parse this using DateTime.Parse(string). Currently for some dates it works and for others it throws Exception. How do I handle this? How do I make sure that no matter what format is provided it always parses correct (as long as it is valid date)?
Thanks in advance :)
EDIT
As there is no fix answer to it I modify my question to ask how do I convert it to MM/DD/YYYY? What should I provide in IFormat开发者_开发百科Provider of DateTime.Parse?
DateTime needs to know how to parse the date otherwise it won't know whether 05/07/2011 is the 5th July or the 7th May. Wouldn't it be better to use a calendar control to remove this ambiguity?
I suggest using a fixed format. You may even allow your users to select the format they want to use. But you absolutely need to know the format. Then you could use DateTime.TryParseExact
. For instance, what would 01/03/2011 mean? It could be mm/dd/yyyy or dd/mm/yyyy. You really need to be explicit about this.
I came here to figure out if I can find a better solution than mine. I already saw some of this solution propose here in other post and google. What IMHO works better is follow:
DateTime date;
bool isDate = (DateTime.TryParseExact(txtbxDATETIME.Value,
"yyyy'/'MM'/'dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date));
//possible use:
DateTime someDATEorVAr = (isDate) ? date : DateTime.Now;
Hope somebody find this useful
That parsing problem can be solved by using the TryParse(String, IFormatProvider, DateTimeStyles, DateTime) variant so that culture info (most commonly I use CultureInfo.CurrentCulture) can be passed to it and thus removing the ambiguity.
DateTime.TryParse
Vijay
精彩评论