1、DateTime合法的范围
DateTime是值类型,表示值范围在0001/1/1 00:00:00到9999/12/31 23:59:59之间的日期和时间。
2、平年和闰年
概述:闰年有366天,2月有29天,每四年才有一次闰年。如果这个年能被4整除,那么这年就是闰年;如果是整百数,需要整除400才为闰年。
地球绕太阳公转一周叫做一回归年,一回归年长365日5时48分46秒。因此,公历规定有平年和闰年,平年一年有365日,比回归年短0.2422日,四年共短0.9688日,故每四年增加一日,这一年有366日,就是闰年。但四年增加一日比四个回归年又多0.0312日,400年后将多3.12日,故在400年中少设3个闰年,也就是在400年中只设97个闰年,这样公历年的平均长度与回归年就相近似了。由此规定:年份是整百数的必须是400的倍数才是闰年,例如1900年、2100年就不是闰年。
释意:
平年:指阳历没有闰日或农历没有闰月的年份。
闰年:闰年是公历中的名词。凡阳历中有闰日(二月为二十九日)的年,闰余(岁余置闰。阴历每年与回归年相比所差的时日)。
平年和闰年的判断方法:不是闰年的年份就是平年。
闰年的判断方法:闰年分为普通闰年和世纪闰年。
普通闰年:能被4整除但不能被100整除的年份为普通闰年。
世纪闰年:能被400整除的为世纪闰年。
3、正则表达式
验证yyyy年份:
\d{3}[1-9]|\d{2}[1-9]\d|\d[1-9]\d{2}|[1-9]\d{3}
验证MMdd月日:
大月(1、3、5、7、8、10、12月,有31天)
(0[13578]|1[02])(0[1-9]|[12]\d|3[01])
小月(4、6、9、11月,有30天)
(0[469]|11)(0[1-9]|[12]\d|30)
平年2月(有28天)
02(0[1-9]|[1]\d|2[0-8])
闰年:
能被4整除但不能被100整除的年份
(\d{2})(0[48]|[2468][048]|[13579][26])
能被400整除的年份
((0[48]|[2468][048]|[3579][26])00)
闰年2月(有29天)
((\d{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229
最终,验证yyyyMMdd的正则表达式为
((\d{3}[1-9]|\d{2}[1-9]\d|\d[1-9]\d{2}|[1-9]\d{3})(((0[13578]|1[02])(0[1-9]|[12]\d|3[01]))|((0[469]|11)(0[1-9]|[12]\d|30))|(02(0[1-9]|[1]\d|2[0-8]))))|(((\d{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)
4、举例
private static string input = @"\\172.39.0.47\r$\Image\20160511\0000007\2016(测试).jpg";
/// <summary>
/// 获取yyyyMMdd部分,结果为20160511
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string TryGetDateStr(string input)
{
Regex regex = new Regex(@"((\d{3}[1-9]|\d{2}[1-9]\d|\d[1-9]\d{2}|[1-9]\d{3})(((0[13578]|1[02])(0[1-9]|[12]\d|3[01]))|((0[469]|11)(0[1-9]|[12]\d|30))|(02(0[1-9]|[1]\d|2[0-8]))))|(((\d{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)");
var match = regex.Match(input);
if (match.Success && match.Index >= 0)
{
return match.Value;
}
return string.Empty;
}
/// <summary>
/// 获取yyyyMMdd前面的部分,结果为\\172.39.0.47\r$\Image\
/// </summary>
/// <param name="input"></param>
/// <param name="str"></param>
/// <returns></returns>
public static bool TryGetDatePreStr(string input, out string str)
{
//https://my.oschina.net/j4love/blog/4681714
Regex regex = new Regex(@"((\d{3}[1-9]|\d{2}[1-9]\d|\d[1-9]\d{2}|[1-9]\d{3})(((0[13578]|1[02])(0[1-9]|[12]\d|3[01]))|((0[469]|11)(0[1-9]|[12]\d|30))|(02(0[1-9]|[1]\d|2[0-8]))))|(((\d{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)");
var match = regex.Match(input);
if (match.Success && match.Index >= 0)
{
str = input.Substring(0, match.Index);
return true;
}
str = "";
return false;
}