C#對DateTime類型的操作總結

來源:互聯網
上載者:User

一、取某月的最後一天
法一、使用算出該月多少天,年+月+加上多少天即得,舉例取今天這個月的最後一天

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)  便能取出他們之間時間差的分鐘總數,已經幫你換算好了,對於要求規定單位,時、分、秒特別有用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.