我想让日期函数识别 "20081101" 这样的日期格式.
在下面的代码中: class myDateTimea
{
public static DateTime Parse(string s)
{
if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
s = s.Substring(0, 4) + "-" + s.Substring(4, 2) + "-" + s.Substring(6, 2);
try
{
return DateTime.Parse(s);
}
catch
{
//日期格式不正确
//return null;
}
}
}如果在 catch 里不写返回语句,会提示:"并非所有路径都返回值"
如果加 return null,会提示:"错误 1 无法将 NULL 转换成“System.DateTime”,因为它是一种值类型"如果加的话,不知道加个什么返回值.
这样的问题该如何解决?
谢谢大家?
在下面的代码中: class myDateTimea
{
public static DateTime Parse(string s)
{
if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
s = s.Substring(0, 4) + "-" + s.Substring(4, 2) + "-" + s.Substring(6, 2);
try
{
return DateTime.Parse(s);
}
catch
{
//日期格式不正确
//return null;
}
}
}如果在 catch 里不写返回语句,会提示:"并非所有路径都返回值"
如果加 return null,会提示:"错误 1 无法将 NULL 转换成“System.DateTime”,因为它是一种值类型"如果加的话,不知道加个什么返回值.
这样的问题该如何解决?
谢谢大家?
你在catch里边返回个当前日期就行了
另外,要识别"20081101"这种格式不用这么麻烦的 string str = "20081101";
DateTime dt = DateTime.ParseExact(str, "yyyyMMdd", null);
然后使用这个方法的代码再对异常进行处理
try
{
return DateTime.Parse(s);
}
catch
{
//日期格式不正确
throw new ArgumentException("Invalid input string");
}
改为
return new DateTime();
下面就可以正确运行了。
class myDateTimea
{
public static DateTime? Parse(string s)
{
if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
s = s.Substring(0, 4) + "-" + s.Substring(4, 2) + "-" + s.Substring(6, 2);
try
{
return DateTime.Parse(s);
}
catch
{
return null;
}
}
}
public static DateTime? Parse(string s)
{
DateTime? dt = null;
if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
s = s.Substring(0, 4) + "-" + s.Substring(4, 2) + "-" + s.Substring(6, 2);
try
{
dt = DateTime.Parse(s);
return dt;
}
catch
{
//日期格式不正确
return dt;
}
}
如:
return DateTime.MinValue ;----------------建议用DateTime.TryParseExact来转换,不需要自己写解释代码。
string dateTimeString = "20080101";
DateTime dateTime ;
if (DateTime.TryParseExact(dateTimeString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
//....
};
正解你写的是属性方法,作为任何属性方法都要返回对应属性类型的对象
即
public static DateTime DateTimeParser(string s){
DateTime dt = null;
if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
{}else{}try{}catch{}return dt
//1.这是一种在开始声明一个对象,赋值完成所有步骤,在结尾返回
//2.在判断中,循环中,异常捕获中, throw new Exception可以被处理,但不能直接在某处返回一个值
if中return ;else中也要return ,道理很简单,try正常得到值,但catch不返回值会有空引用一样
}
return null 类型不一致
正确的:return DateTime类型的