快速计算两个日期之间的天数 [英] Calculating the number of days between two dates in swift

查看:61
本文介绍了快速计算两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在计算两个日期之间的天数时使用变量 today 而不是 Date() 的结果会在 swift 中产生差异?

Why does the result of using the variable today rather than Date() when calculating the number of days between two dates make a difference in swift?

var numDays: Int
var today = Date()
var twoWeeksFromNow: Date = Calendar.current.date(byAdding: .day, 
value: 14, to: Date())!

var numDaysWithDate: Int = 
Calendar.current.dateComponents([.day], from: Date(), to: 
twoWeeksFromNow).day!
var numDaysWithToday: Int = 
Calendar.current.dateComponents([.day], from: today, to: 
twoWeeksFromNow).day!

print(numDaysWithDate) // 13
print(numDaysWithToday) // 14

推荐答案

这与您创建变量并比较它们的顺序有关.

It has to do with the order that you're creating your variables and comparing them.

您要做的第一件事是创建今天.然后,您创建 twoWeeksFromNow,基于一个新的 Date(),它将在未来比 今天稍微> 是.在我的机器上,在操场上,第二次约会比第一次晚了大约 300 微秒.

The first thing you do is create today. Then, you create twoWeeksFromNow, based on a new Date() that will be slightly further in the future than today was. On my machine, in a playground, the second date is about 300 microseconds further in the future than the first.

然后,对于numDaysWithDate,您将twoWeeksFromNow另一个 新的Date() 进行比较,甚至更多稍微在未来.因此,您的时间框架非常不到整整 2 周,给您 13 天.

Then, for numDaysWithDate, you compare twoWeeksFromNow to another new Date(), even more slightly in the future. So, your time frame is very slightly less than 2 full weeks, giving you 13 days.

但是,对于 numDaysWithToday,您将 twoWeeksFromNow 与原始 today 进行比较,后者是 before >twoWeeksFromNow 是,让它稍微超过 2 周,给你 14 天.

But, for numDaysWithToday, you compare twoWeeksFromNow with the original today, which was created before twoWeeksFromNow was, making it slightly longer than 2 weeks, giving you 14 days.

如果您更改 todaytwoWeeksFromNow 声明的顺序,您会看到不同的结果:

If you change the order of the the today and twoWeeksFromNow declarations, you can see a different result:

var twoWeeksFromNow: Date = Calendar.current.date(byAdding: .day,
value: 14, to: Date())!
var today = Date()

现在,因为 today 的创建日期比 twoWeeksFromNow 的创建日期稍晚,所以两个结果都是 13.

Now, because today was created slightly later than the date that twoWeeksFromNow was created from, both results are 13.

这篇关于快速计算两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆