C#和Sql的時間操做心得(一) 最近折騰什麼週期性工做安排,對時間的操做增強了一點,得出在應用軟件中時間真是個注意的地方,像客戶要求「2006-03-16 12:00:00」 或者是「2006年03月16日 12:00:00」 。他們說到很簡單,可是落實到咱們這裏不是很可貴活,可是心情上老是有點煩躁,在此,我爲天下程序員打抱個不平。嘿嘿,固然,俺也自我安慰一下,言歸正傳,我把時間操做的心得貼出來,共享之:程序員
1、取某月的最後一天 法1、使用算出該月多少天,年+月+加上多少天即得,舉例取今天這個月的最後一天函數
private void GetLastDateForMonth(DateTime DtStart,out DateTime DtEnd) { int Dtyear,DtMonth;io
DtStart = DateTime.Now; Dtyear = DtStart.Year; DtMonth = DtStart.Month;ast
int MonthCount = DateTime.DaysInMonth(Dtyear,DtMonth); DtEnd = Convert.ToDateTime(Dtyear.ToString()+"-"+DtMonth.ToString()+"-"+MonthCount);軟件
}date
法2、取出下月的第一天減去一天即是這個的最後一天程序
private void GetLastDateForMonth(DateTime DtStart,out DateTime DtEnd) { int Dtyear,DtMonth;方法
DtStart = DateTime.Now.AddMonths(1); Dtyear = DtStart.Year; DtMonth = DtStart.Month;im
DtEnd = Convert.ToDateTime(Dtyear.ToString()+"-"+DtMonth.ToString()+"-"+"1").AddDays(-1);d3
}
2、時間差的計算 法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()+"秒";
法2、使用Sql中的DATEDIFF函數 使用方法:DATEDIFF ( datepart , startdate , enddate ) 它能幫你取出你想要的各類形式的時間差,如相隔多少天,多少小時,多少分鐘等,具體格式以下:
日期部分 縮寫 year yy, yyyy quarter qq, q Month mm, m dayofyear dy, y Day dd, d Week wk, ww Hour hh minute mi, n second ss, s millisecond ms
如:datediff(mi,DtOpTime,DtEnd) 便能取出他們之間時間差的分鐘總數,已經幫你換算好了,對於要求規定單位,時、分、秒特別有用
這個先寫到這,待續,都寫完了,後面就沒活了,哈哈