在VB.NET中两个日期之间的时间跨度 [英] Timespan between two dates in VB.NET
问题描述
使用时间跨度计算vb.net中两个日期之间的天数差异
我尝试了什么:
calculate number of days difference between two dates in vb.net using timespan
What I have tried:
Dim d1 As DateTime = "01-Sep-2017"
Dim d2 As DateTime = "30-Sep-2017"
Dim TTF As New TimeSpan
TTF = d2.Subtract(d1)
TTF.TotalDays
TotalDays is 29 days
Dim d1 As DateTime = "15-Sep-2017"
Dim d2 As DateTime = "30-Sep-2017"
Dim TTF As New TimeSpan
TTF = d2.Subtract(d1)
TTF.TotalDays
TotalDays is 15 days
Why difference between "01-Sep-2017" and "30-Sep-2017" 29 days not 30 days because difference between "15-Sep-2017" and "30-Sep-2017" is 15 days. i want number of days between two days.
推荐答案
为什么01-Sep-2017和2017年9月30日之间的差异是30天
Why difference between "01-Sep-2017" and "30-Sep-2017" is 30 days
嗯。根据你的例子,它不是:
Um. It isn't, according to your example:
Dim d1 As DateTime = "01-Sep-2017"
Dim d2 As DateTime = "30-Sep-2017"
Dim TTF As New TimeSpan
TTF = d2.Subtract(d1)
TTF.TotalDays
TotalDays is 29 days
如果我理解你,你想要包括这一天结束了时间段。所以,你必须在结果中加1。
OriginalGriff已经在回答的评论中提到了(但换句话说)。
If i understand you well, you want to include the day, which ends time period. So, you have to add 1 to the result.
OriginalGriff has already mentioned that (but in other words) in the comment to his answer.
OriginalGriff 2小时10分钟前
回复
[修改评论。] [删除评论。]
这就是你得到的。
30 - 15 == 15
30 - 1 == 29.
为什么你会期望它有什么不同?
如果你想要一个月的天数,你需要从A +月的第一个月中减去A月的第一个 1不是第一个月A从月末A
OriginalGriff 2hrs 10mins ago
Reply
[Modify the comment.] [Delete the comment.]
And that is what you get.
30 - 15 == 15
30 - 1 == 29.
Why would you expect it to be any different?
If you want the number of days in a month you need to subtract "first of month A" from "first of month A + 1" not "first of month A" from "last of month A"
检查:
Check this:
Dim d1 As DateTime = "01-Sep-2017"
Dim d2 As DateTime = "30-Sep-2017"
Dim result = (d2-d1).TotalDays + 1
Console.WriteLine("The difference between date: {0} and {1} is {2} days.", d1, d2, result)
我强烈建议您阅读:执行算术运算日期和时间| Microsoft Docs [ ^ ]
代码总共返回29天,您可以在30天内分享更多详细信息吗?
The code returns 29 total days, can you share more details where you are seeing 30 days?
Dim d1 As DateTime = "01-Sep-2017"
Dim d2 As DateTime = "30-Sep-2017"
Dim TTF As New TimeSpan
TTF = d2.Subtract(d1)
TTF.TotalDays
这篇关于在VB.NET中两个日期之间的时间跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!