获得与.NET约会的最佳方式? [英] Best way to get a date with .NET?

查看:154
本文介绍了获得与.NET约会的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个字符串从我的页面回来了,我想,以确保它是一个日期。这是我迄今(它的工作),我只是想知道这是否是最佳的方式来做到这一点。我使用.NET 4

  INT TheMonth = 0;
INT TheDay = 0;
INT的某些地方= 0;
日期时间NewDate;。VAR TheIncomingParam = Request.Params.Get(__ EVENTARGUMENT)的ToString();的char [] TheBreak = {'/'};
字符串[] = TheOutput TheIncomingParam.Split(TheBreak);尝试{TheMonth = Convert.ToInt32(TheOutput [0]); }
赶上{}尝试{TheDay = Convert.ToInt32(TheOutput [1]); }
赶上{}尝试{的某些地方= Convert.ToInt32(TheOutput [2]); }
赶上{}如果(TheMonth = 0&放大器;!&放大器; TheDay = 0&放大器;!&放大器;!的某些地方= 0)
{
        尝试{NewDate =新日期时间(的某些地方,TheMonth,TheDay); }
        抓{VAR野点= TRUE; }
}


解决方案

使用上定​​义的解析方法之一的DateTime 结构。

如果该字符串不是可解析这些将抛出一个异常,那么您可能需要使用的 的TryParse 替代方法(而不是pretty - 他们需要一个输出参数,但更安全):

  DateTime的数值指明MyDate;
如果(DateTime.TryParse(dateString,
                  CultureInfo.InvariantCulture,
                  DateTimeStyles.None,
                  出数值指明MyDate))
{
   //使用数值指明MyDate在这里,因为它成功解析
}

如果您知道的日期通过的确切格式,你可以尝试使用 ParseExact TryParseExact 的采取的日期和时间格式字符串(标准或的自定义)当试图解析日期字符串

I'm getting a string back from my page and I want to make sure it's a date. This is what I have so far (it works) and I just want to know if this is the "best" way to do it. I'm using .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; }
}

解决方案

Use one of the Parse methods defined on the DateTime structure.

These will throw an exception if the string is not parseable, so you may want to use one of the TryParse methods instead (not as pretty - they require an out parameter, but are safer):

DateTime myDate;
if(DateTime.TryParse(dateString, 
                  CultureInfo.InvariantCulture, 
                  DateTimeStyles.None, 
                  out myDate))
{
   // Use myDate here, since it parsed successfully
}

If you know the exact format of the passed in date, you can try using the ParseExact or TryParseExact that take date and time format strings (standard or custom) when trying to parse the date string.

这篇关于获得与.NET约会的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆