如何获得两个日期之间的月份持续时间..? [英] How to get duration of the months between two dates..?
本文介绍了如何获得两个日期之间的月份持续时间..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得两个日期之间的总月数.
示例:date1 = 2011年7月15日
date2 = 25/08/2011
Hi,
How to get total months in between two dates.
Example : date1 = 15/07/2011
date2 = 25/08/2011
How to get duration of the months these two dates..?
推荐答案
try
给定语法
try
given Syntax
DATEDIFF(datepart, startdate, enddate)
例子
example
SELECT DATEDIFF(MONTH, date1, date2)
或
or
SELECT DATEDIFF(MONTH, 15/07/2011,25/08/2011)
并不是那么简单:由于月份不是固定长度,所以不能使用时间跨度:相差29天,可能是1天一个月,一个月还是一个月,取决于您在一年中的什么时候.
因此,请尝试:
It''s not that simple: since months are not a fixed length, you can''t use a timespan: is the difference is 29 days, it could be one month, or none, depending on when in the year your are.
So, try:
string date1 = "15/07/2011";
string date2 = "25/08/2011";
DateTime d1 = DateTime.ParseExact(date1, "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime d2 = DateTime.ParseExact(date2, "dd/MM/yyyy", CultureInfo.InvariantCulture);
int months = d2.Month - d1.Month + (d2.Year -d1.Year) * 12;
TimeSpan ts = (25/08/2011 - 25/08/2011);
months=ts.Days/30;
这篇关于如何获得两个日期之间的月份持续时间..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文