我以前所做的是使用时间戳,然后添加 86400 秒 ( 24 * 60 * 60 )。当我在 stackoverflow 上读到最近的一个问题时,注意到这并不是每天都正确的,我想改变这一点。
所以我接下来想到的是使用 NSDateComponents。我只是获取当前日期并加 1。现在我想知道这有多“智能”。就像如果天等于 31 一样,它是否将天设置为 1,将月份设置为 +1(或者再次设置为 12 到 1 时)?我可以手动执行此操作,但这只适用于公历,所以我真的不知道这是否是一个好的解决方案。
What I used to do was using the timestamp and then adding 86400 seconds ( 24 * 60 * 60 ). As I read a recent question on stackoverflow noting that that is not correct for every day, I want to change this.
So the next thing I came up with was by using NSDateComponents. I simply get the current day and add 1. Now I was wondering how "smart" that is. Like if the day is equal to 31, does it set the day to 1 and the month to whatever it is +1 ( or when it is 12 to 1 again ) ? I can do this manually but that would only work properly for the gregorian calendar so I don't really know whether that would be a good solution either..
发布评论
评论(2)
它很聪明,除非你想让它变得愚蠢。
来自
-[NSCalendar 的文档dateByAddingComponents:toDate:options]
:如果您不希望单位溢出到更高的单位,那么您可以传递“
NSWrapCalendarComponents
”作为options:
参数的值。It is smart, unless you want it to be dumb.
From the documentation for
-[NSCalendar dateByAddingComponents:toDate:options]
:If you did not want units overflowing into higher units, then you would pass "
NSWrapCalendarComponents
" as the value of theoptions:
parameter.请务必小心夏令时。不同时区的情况有所不同。 并且发生在午夜
我相信,如果您通过addingComponents:toDate:options 调用 [NSCalendar date] 并且您的日期在晚上 11-12 点之间,那么您可能会因为 DST 而错过或重新运行一天。
为了解决这个问题,建议将日期更改为当天中午,然后添加日期。
我不确定 options:0 设置,但我确实对此进行了相当彻底的测试。我用它来获取 10 天日期的数组。它可以正确地包裹各种日/月/年的不连续性。如果您想测试一下,请在应用商店中查看 SunPose Rise Set。 (是的,它是免费的)
Be very careful of DST. It is different for various time zones. AND It happens at Midnight
I believe that if you call [NSCalendar date by addingComponents:toDate:options] and your date is between 11-12 pm, you risk missing or re-running a day because of DST.
To get around this, is suggest changing your date to noon on the day and then adding the day.
I'm not sure about the options:0 setting, but I did test this pretty thoroughly. I use it to get an array of with 10 days of dates. It gives correct wrapping around the various day/month/year discontinuities. Check out SunPose Rise Set on the app store if you want to test it. (yes, it's free)