可能重复:
How to get difference between two dates in Year/Month/Week/Day?
我对两个日期之间的区别有疑问。
我需要输入0 YEAR, 0 MONTHS, 0 DAYS LEFT
m例如:
1 YEAR, 2 MONTHS, 3 DAYS LEFT
使用dateDiff功能或使用其他任何功能都无法实现。
答案 0 :(得分:0)
使用DateTime作为表示,您可以使用以下内容:
dim test as DateTime = DateTime.Now
dim test2 as DateTime = DateTime.Now.AddDays(2)
dim result as TimeSpan = test.Subtract(test2)
dim hours as Integer = result.Hours
dim days as Integer = result.Days
int years=days mod 365
days=days-years*365
答案 1 :(得分:0)
这样的事情:
' A Start date an end Date to test with
Dim StartingDate As DateTime = DateTime.Now
Dim TargetEndDate As DateTime = DateTime.Now.AddYears(1).AddDays(5).AddMinutes(45)
' Get the difference between the two dates, and Create a new Date containing just the total days
Dim DifferenceBetweenDates As TimeSpan = TargetEndDate.Subtract(StartingDate)
Dim DiffFromSystemDate As New DateTime(0, 0, DifferenceBetweenDates.TotalDays)
' Get the number of years, months and days left
Dim NumberOfYears As Integer = DiffFromSystemDate.Year - 1
Dim NumberOfMonths As Integer = DiffFromSystemDate.Month - 1
Dim NumberOfDays As Integer = StartingDate.Day - DateTime.DaysInMonth(StartingDate.Year, StartingDate.Month)
' Build up the result string
Dim Result As String = String.Format("{0} YEAR, {1} MONTHS, {3} DAYS LEFT", NumberOfYears, NumberOfMonths, NumberOfDays)
请参阅副本中的JonSkeets帖子,以便更好地执行此操作
答案 2 :(得分:0)
我在某个时候遇到了同样的问题并找到了一个解决方案。 请记住d1是endDate,d2是startDate。 d1> D2
public static void TimeSpanToDate(DateTime d1, DateTime d2, out int years, out int months, out int days)
{
// compute & return the difference of two dates,
// returning years, months & days
// d1 should be the larger (newest) of the two dates
// we want d1 to be the larger (newest) date
// flip if we need to
if (d1 < d2)
{
DateTime d3 = d2;
d2 = d1;
d1 = d3;
}
// compute difference in total months
months = 12 * (d1.Year - d2.Year) + (d1.Month - d2.Month);
// based upon the 'days',
// adjust months & compute actual days difference
if (d1.Day < d2.Day)
{
months--;
days = DateTime.DaysInMonth(d2.Year, d2.Month) - d2.Day + d1.Day;
}
else
{
days = d1.Day - d2.Day;
}
// compute years & actual months
years = months / 12;
months -= years * 12;
}
它适用于我。
希望它有所帮助。
普利文