与.NET约会的最佳方式?
我从我的页面回来了一个字符串,我想确定它是一个约会。 这是我到目前为止(它的工作原理),我只是想知道这是否是“最好”的方法。 我正在使用.NET 4。
int TheMonth =0; int TheDay = 0; int TheYear = 0; DateTime NewDate; var TheIncomingParam = Request.Params.Get("__EVENTARGUMENT").ToString(); char[] TheBreak = { '/' }; string[] TheOutput = TheIncomingParam.Split(TheBreak); try { TheMonth = Convert.ToInt32(TheOutput[0]); } catch { } try { TheDay = Convert.ToInt32(TheOutput[1]); } catch { } try { TheYear = Convert.ToInt32(TheOutput[2]); } catch { } if (TheMonth!=0 && TheDay!=0 && TheYear!=0) { try { NewDate = new DateTime(TheYear, TheMonth, TheDay); } catch { var NoDate = true; } }
使用DateTime
结构上定义的Parse
方法之一。
如果字符串不可解析,这些将抛出exception,因此您可能希望使用其中一个TryParse
方法(不是很漂亮 – 它们需要out参数,但更安全):
DateTime myDate; if(DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate)) { // Use myDate here, since it parsed successfully }
如果您知道传入日期的确切格式,则可以尝试使用在尝试解析日期字符串时使用日期和时间格式字符串( 标准或自定义 )的ParseExact
或TryParseExact
。
DateTime.TryParse和DateTime.TryParseExact怎么样?
第一个使用当前的文化日期格式。
.NET为我们提供了datetime.parse
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
和datetime.tryparse
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
这两种方法都是从字符串中解析日期的好方法
我只想TryParse输入字符串:
private bool ParseDateString() { var theIncomingParam = Request.Params.Get("__EVENTARGUMENT").ToString(); DateTime myDate; if (DateTime.TryParse(theIncomingParam, CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate)) { int TheMonth = myDate.Month; int TheDay = myDate.Day; int TheYear = myDate.Year; // TODO: further processing of the values just read return true; } else { return false; } }
对于URL: 使用日期iso formate( YYYYMMDD
)
转换:
datetime.TryParse如上所述