年月日中两个日期之间的差异
问题描述:
你好先生
我有两个约会,例如:
Hello Sir
I have two date like:
dt1=01-Jan-2012<br />
dt2=08-Feb-2012<br />
我将如何计算将显示休息日的日期差.表示当月结束后,休息日部分将显示,例如如果d2-d1
则应为1个月7天,那么我将仅获取7天内的天.
我做过这样的事情:
How I will calculate the date difference that it will show the rest day. Means after completion of the month the rest day part will show, e.g. if d2-d1
then it should be 1 month 7 days, then i will fetch only day means 7 days.
I have done like:
DateTime fromdate = Convert.ToDateTime(txtFromDate.Text.Trim()).Date;
DateTime todate = Convert.ToDateTime(txtToDate.Text.Trim()).Date;
TimeSpan tot_days = todate.Subtract(fromdate);
int days = Convert.ToInt32(tot_days.Days);
但显示的是包括月份在内的总天数.
所以帮帮我.
but it is showing total days including month.
So help me.
Thanks.
答
当tm1 and tm2
之间的时间间隔大于one month
时,由 JF2015 给出的Solution 1
很好.但是当期限少于一个月时,例如tm1=15-Jan-2012
和tm2=08-Feb-2012
,它将返回Months: 1 Days: -7
.
我认为,当period is more than one month and when the period is less than a month
时,以下代码均可同时使用.
TheSolution 1
given by JF2015 is good when the period betweentm1 and tm2
is greater thanone month
. But when the period is less than one month saytm1=15-Jan-2012
andtm2=08-Feb-2012
, it returnsMonths: 1 Days: -7
.
I think the following code can be used for both when theperiod is more than one month and when the period is less than a month
.
DateTime date1 = DateTime.ParseExact("15-Jan-2012","d-MMM-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime date2 = DateTime.ParseExact("08-Feb-2012","d-MMM-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
while(date1.AddMonths(1) < date2){
date1 = date1.AddMonths(1);
}
int days = date2.Subtract(date1).Days;
Console.WriteLine (days);
//days = 24
//days = 7 when date1= 01-Jan-2012
public void TestFunc()
{
DateTime tm1 = Convert.ToDateTime("01-Jan-2012");
DateTime tm2 = Convert.ToDateTime("08-Feb-2012");
TimeSpan span = tm2 - tm1;
int mDiff = MonthDifference(tm2, tm1);
double dDiff = (tm2 - tm1.AddMonths(mDiff)).TotalDays;
MessageBox.Show("Months: " + mDiff + " Days " + dDiff);
}
public int MonthDifference(DateTime lValue, DateTime rValue)
{
return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);
}
DATEDIFF()函数 [ ^ ]
DATEDIFF(Transact-SQL) [ DATEDIFF:日期差 [
DATEDIFF() Function[^]
DATEDIFF (Transact-SQL)[^]
DATEDIFF: date difference[^]