c# DateTime常用操作实例(datetime计算时间差)
#region datetime操作
public class c3
{
//datetime常用的操作
public static void fun1()
{
//格式:2012-8-16 11:21:29
console.writeline("当前时间:{0}", datetime.now.tostring());
//格式:2012-8-16 0:00:00
console.writeline("日期部分:{0}", datetime.now.date.tostring());
//格式:11:21:29
console.writeline("时间部分:{0}", datetime.now.tolongtimestring());
//获取此实例的当天的时间。相当的精确【到毫秒】
console.writeline("timeofday:{0}", datetime.now.timeofday.tostring());
console.writeline("取中文日期显示_年月日时分:{0}", datetime.now.tostring("f"));
console.writeline("取中文日期显示_年月:{0}", datetime.now.tostring("y"));
console.writeline("取中文日期显示_月日:{0}", datetime.now.tostring("m"));
console.writeline("取中文年月日:{0}", datetime.now.tostring("d"));
//取当前时分,格式为:14:24
console.writeline("取当前时分:{0}", datetime.now.tostring("t"));
//取当前时间,格式为:2003-09-23t14:46:48
console.writeline("取当前时分:{0}", datetime.now.tostring("s"));
//取当前时间,格式为:2003-09-23 14:48:30z
console.writeline("取当前时分:{0}", datetime.now.tostring("u"));
//取当前时间,格式为:2003-09-23 14:48
console.writeline("取当前时分:{0}", datetime.now.tostring("g"));
//取当前时间,格式为:tue, 23 sep 2003 14:52:40 gmt
console.writeline("取当前时分:{0}", datetime.now.tostring("r"));
//获得当前时间 n 天后的日期时间
datetime newday = datetime.now.adddays(100);
console.writeline(newday.tostring());
console.writeline("年:{0}", datetime.now.year.tostring());
console.writeline("月:{0}", datetime.now.month.tostring());
console.writeline("日:{0}", datetime.now.day.tostring());
console.writeline("时:{0}", datetime.now.hour.tostring());
console.writeline("分:{0}", datetime.now.minute.tostring());
console.writeline("秒:{0}", datetime.now.second.tostring());
console.writeline("毫秒:{0}", datetime.now.millisecond.tostring());
console.writeline("计时周期数:{0}", datetime.now.ticks.tostring());
console.writeline("星期:{0}", datetime.now.dayofweek.tostring());
console.writeline("一年中的第几天:{0}", datetime.now.dayofyear.tostring());
}
//客户端代码
public static void myfun()
{
//struct本身是一个结构体
//datetime dt0 = new datetime();
datetime dt1 = new datetime(2012, 8, 14, 10, 54, 55);
datetime dt2 = new datetime(2012, 12, 21);//2012-12-21 00:00:00
console.writeline(datediff(dt1, dt2));
//我活了多少天了
datetime dt3 = new datetime(2012, 8, 14, 12, 00, 00);
datetime dt4 = new datetime(1990, 11, 17, 02, 48, 00);//2012-12-21 00:00:00
console.writeline("我活了多少天" + datediff(dt4, dt3));
}
//计算时间的差值
public static string datediff(datetime datetime1, datetime datetime2)
{
string datediff = null;
timespan ts1 = new timespan(datetime1.ticks);
timespan ts2 = new timespan(datetime2.ticks);
timespan ts = ts1.subtract(ts2).duration();
datediff = ts.days.tostring() + "天" + ts.hours.tostring() + "小时" + ts.minutes.tostring() + "分钟" + ts.seconds.tostring() + "秒";
return datediff;
#region note
//c#中使用timespan计算两个时间的差值
//可以反加两个日期之间任何一个时间单位。
//timespan ts = date1 - date2;
//double ddays = ts.totaldays;//带小数的天数,比如1天12小时结果就是1.5
//int ndays = ts.days;//整数天数,1天12小时或者1天20小时结果都是1
#endregion
}
}
#endregion