C#和Sql的时间操作心得(一)

最近折腾什么周期性工作安排,对时间的操作加强了一点,得出在应用软件中时间真是个注意的地方,像客户要求“2006-03-16 12:00:00” 或者是“2006年03月16日 12:00:00” 。他们说到很简单,但是落实到我们这里不是很难得活,但是心情上总是有点烦躁,在此,我为天下程序员打抱个不平。嘿嘿,当然,俺也自我安慰一下,言归正传,我把时间操作的心得贴出来,共享之:

一、取某月的最后一天
法一、使用算出该月多少天,年+月+加上多少天即得,举例取今天这个月的最后一天

private void GetLastDateForMonth(DateTime DtStart,out DateTime DtEnd)
  {
   int Dtyear,DtMonth;

   DtStart = DateTime.Now;
   Dtyear  = DtStart.Year;
   DtMonth = DtStart.Month;

   int MonthCount = DateTime.DaysInMonth(Dtyear,DtMonth);
   DtEnd = Convert.ToDateTime(Dtyear.ToString()+"-"+DtMonth.ToString()+"-"+MonthCount);

  }

法二、取出下月的第一天减去一天便是这个的最后一天

private void GetLastDateForMonth(DateTime DtStart,out DateTime DtEnd)
  {
   int Dtyear,DtMonth;

   DtStart = DateTime.Now.AddMonths(1);
   Dtyear  = DtStart.Year;
   DtMonth = DtStart.Month;
   
   DtEnd = Convert.ToDateTime(Dtyear.ToString()+"-"+DtMonth.ToString()+"-"+"1").AddDays(-1);

  }

 二、时间差的计算
法一、使用TimeSpan ,同时也介绍一下TimeSpan的用法
 
相关属性和函数

Add:与另一个TimeSpan值相加。
Days:返回用天数计算的TimeSpan值。
Duration:获取TimeSpan的绝对值。
Hours:返回用小时计算的TimeSpan值
Milliseconds:返回用毫秒计算的TimeSpan值。
Minutes:返回用分钟计算的TimeSpan值。
Negate:返回当前实例的相反数。
Seconds:返回用秒计算的TimeSpan值。
Subtract:从中减去另一个TimeSpan值。
Ticks:返回TimeSpan值的tick数。
TotalDays:返回TimeSpan值表示的天数。
TotalHours:返回TimeSpan值表示的小时数。
TotalMilliseconds:返回TimeSpan值表示的毫秒数。
TotalMinutes:返回TimeSpan值表示的分钟数。
TotalSeconds:返回TimeSpan值表示的秒数。 
 

简单示例:
DateTime d1 =new DateTime(2004,1,1,15,36,05);
DateTime d2 =new DateTime(2004,3,1,20,16,35);

TimeSpan d3 = d2.Subtract(d1);

LbTime.Text = "相差:"
+d3.Days.ToString()+"天"
+d3.Hours.ToString()+"小时"
+d3.Minutes.ToString()+"分钟"
+d3.Seconds.ToString()+"秒";

法二、使用Sql中的DATEDIFF函数
使用方法:DATEDIFF ( datepart , startdate , enddate )
它能帮你取出你想要的各种形式的时间差,如相隔多少天,多少小时,多少分钟等,具体格式如下:

日期部分缩写
yearyy, yyyy
quarterqq, q
Monthmm, m
dayofyeardy, y
Daydd, d
Weekwk, ww
Hourhh
minutemi, n
secondss, s
millisecondms


如:datediff(mi,DtOpTime,DtEnd)  便能取出他们之间时间差的分钟总数,已经帮你换算好了,对于要求规定单位,时、分、秒特别有用


这个先写到这,待续,都写完了,后面就没活了,哈哈
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值