一、取某月的最後一天
法一、使用算出該月多少天,年+月+加上多少天即得,舉例取今天這個月的最後一天
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 )
它能幫你取出你想要的各種形式的時間差,如相隔多少天,多少小時,多少分鐘等,具體格式如下:
日期部分 |
縮寫 |
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) 便能取出他們之間時間差的分鐘總數,已經幫你換算好了,對於要求規定單位,時、分、秒特別有用