C#和Sql的時(shí)間操作

字號:

最近折騰什么周期性工作安排,對時(shí)間的操作加強(qiáng)了一點(diǎn),得出在應(yīng)用軟件中時(shí)間真是個(gè)注意的地方,像客戶要求“2006-03-16 12:00:00” 或者是“2006年03月16日 12:00:00” 。他們說到很簡單,但是落實(shí)到我們這里不是很難得活,但是心情上總是有點(diǎn)煩躁,在此,我為天下程序員打抱個(gè)不平。嘿嘿,當(dāng)然,俺也自我安慰一下,言歸正傳,我把時(shí)間操作的心得貼出來,共享之:
    一、取某月的最后一天
    法一、使用算出該月多少天,年+月+加上多少天即得,舉例取今天這個(gè)月的最后一天
    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);
     }
    法二、取出下月的第一天減去一天便是這個(gè)的最后一天
    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);
     }
    二、時(shí)間差的計(jì)算
    法一、使用TimeSpan ,同時(shí)也介紹一下TimeSpan的用法
    相關(guān)屬性和函數(shù)
    Add:與另一個(gè)TimeSpan值相加。
    Days:返回用天數(shù)計(jì)算的TimeSpan值。
    Duration:獲取TimeSpan的絕對值。
    Hours:返回用小時(shí)計(jì)算的TimeSpan值
    Milliseconds:返回用毫秒計(jì)算的TimeSpan值。
    Minutes:返回用分鐘計(jì)算的TimeSpan值。
    Negate:返回當(dāng)前實(shí)例的相反數(shù)。
    Seconds:返回用秒計(jì)算的TimeSpan值。
    Subtract:從中減去另一個(gè)TimeSpan值。
    Ticks:返回TimeSpan值的tick數(shù)。
    TotalDays:返回TimeSpan值表示的天數(shù)。
    TotalHours:返回TimeSpan值表示的小時(shí)數(shù)。
    TotalMilliseconds:返回TimeSpan值表示的毫秒數(shù)。
    TotalMinutes:返回TimeSpan值表示的分鐘數(shù)。
    TotalSeconds:返回TimeSpan值表示的秒數(shù)。
    簡單示例:
    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()+"小時(shí)"
    +d3.Minutes.ToString()+"分鐘"
    +d3.Seconds.ToString()+"秒";
    法二、使用Sql中的DATEDIFF函數(shù)
    使用方法:DATEDIFF ( datepart , startdate , enddate )
    它能幫你取出你想要的各種形式的時(shí)間差,如相隔多少天,多少小時(shí),多少分鐘等,具體格式如下:
    日期部分 縮寫
    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) 便能取出他們之間時(shí)間差的分鐘總數(shù),已經(jīng)幫你換算好了,對于要求規(guī)定單位,時(shí)、分、秒特別有用