Vb.net中两个日期之间的差异(剩余0年、0个月、0天)
可能重复:Vb.net中两个日期之间的差异(剩余0年、0个月、0天),.net,vb.net,.net,Vb.net,可能重复: 我对两次约会之间的差异有个问题。 我需要投入0年、0个月、0天 1 YEAR, 2 MONTHS, 3 DAYS LEFT 使用dateDiff函数或使用任何其他方法都是不可能的。使用DateTime作为表示形式时,您可以使用如下内容: dim test as DateTime = DateTime.Now dim test2 as DateTime = DateTime.Now.AddDays(2) dim result as TimeSpan = test.Su
我对两次约会之间的差异有个问题。 我需要投入
0年、0个月、0天
1 YEAR, 2 MONTHS, 3 DAYS LEFT
使用dateDiff函数或使用任何其他方法都是不可能的。使用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
大概是这样的:
' 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帖子的副本,了解更好的解决方法我以前也遇到过同样的问题,并找到了一个解决方案。
记住d1是结束日期,d2是开始日期。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;
}
public static void TimeSpanToDate(DateTime d1、DateTime d2、out int years、out int months、out int days)
{
//计算并返回两个日期的差值,
//返回年、月和日
//d1应该是两个日期中较大的(最新的)
//我们希望d1是更大(最新)的日期
//如果我们需要的话,翻一下
如果(d1
这对我来说很好
希望能有帮助
普拉文