String型別的時間轉換成datetime型別,並實現減法
方法:Convert.ToDateTime(string)
string格式有要求,必須是yyyy-MM-dd hh:mm:ss
================================================
DateTime dt1 = Convert.DateTime("2007-8-1");
DateTime dt2 = Convert.DateTime("2007-8-15");
TimeSpan span = dt2.Subtract(dt1);
int dayDiff = span.Days + 1;
計算某年某月的天數
-----------------------------------------------
int days = DateTime.DaysInMonth(2007, 8);
days = 31;
給日期增加一天、減少一天
-----------------------------------------------
DateTime dt =DateTime.Now;
dt.AddDays(1); //增加一天
dt.AddDays(-1);//減少一天
========================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
DateTime t1 = DateTime.Parse("2007-01-01");
DateTime t2 = DateTime.Parse("2006-01-01");
System.TimeSpan t3 = t1 - t2; //兩個時間相減 。預設得到的是 兩個時間之間的天數 得到:365.00:00:00
double getDay = t3.TotalDays; //將這個天數轉換成天數, 返回值是double型別的(其實不必轉換,因為t3預設就是天數) 得到:
double getHours = t3.TotalHours; //將這個天數轉換成小時, 返回值是double型別的
double getMinute = t3.TotalMinutes; //將這個天數轉換成分鐘, 返回值是double型別的
double getSeconds = t3.TotalSeconds; //將這個天數轉換成秒數, 返回值是double型別的
double getMillisecond = t3.TotalMilliseconds; ////將這個天數轉換成毫秒, 返回值是double型別的
Console.WriteLine(t3); //輸出:365.00:00:00
Console.WriteLine(getDay); //輸出:365
Console.WriteLine(getHours); //輸出:8760
Console.WriteLine(getMinute); //輸出:525600
Console.WriteLine(getSeconds); //輸出:31536000
Console.WriteLine(getMillisecond); //輸出:31536000000
Console.ReadKey();
}
}
}