如何设置现有的 NSDate 时间?
如何设置现有 NSDate
的时间?
也就是说,我有一个日期(例如当前日期/时间),但随后想将其设置为特定时间(例如上午 11.23 点)。在目标 C 中执行此操作的最快方法是什么?
我正在查看 NSCalendar
并查看诸如 dateByAddingComponents:toDate:options:
和 dateFromComponents:
之类的方法,但这些似乎并不非常符合我在这里所需要的。例如:
dateFromComponents:
- 我必须计算出所有组件才能使其工作,这似乎有点矫枉过正dateByAddingComponents:toDate:options:
- 我不想添加就我而言,而是“设定”时间。
how do I set an existing NSDate
's time?
That is I have a date (say current date/time), but then want to set this to a specific time (e.g. 11.23am) say. What is the quickest way to do this in objective C?
I'm looking at NSCalendar
and see methods such as dateByAddingComponents:toDate:options:
, and dateFromComponents:
, but these don't seem to quite hit the mark for what I need here. For example:
dateFromComponents:
- I would have to work out all components for this to work which seems like overkilldateByAddingComponents:toDate:options:
- I don't want to ADD in my case but rather "set" the time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我使用 NSUIntegerMax 而不是特定的 OR 组合位掩码,因为它更容易,但如果您想指定接收哪些数据组件,请成为我的客人。
I use
NSUIntegerMax
instead of specific OR-combined bit masks because it's easier, but if you want to specify which data components to receive, be my guest.iOS 7 注意:我将其放在其中几个问题中,因为 NSUIntegerMax 的使用似乎不再适用于 iOS7,并且使用它导致我追了大约 3 个小时。我刚刚发现,当我使用
NSUIntegerMax
时,NSDateComponents
忽略设置的年份。例如,这不会改变年份:而这会改变年份:
这可能是 iOS7 的错误,或者可能是使用 NSUIntegerMax 工作只是侥幸,不再有效。我将提交错误报告并得到明确的答案。
无论如何,如果您想避免意外的后果,请指定所有组件,否则您可能会陷入困境!
iOS 7 Note: I'm putting this in a few of these questions because use of NSUIntegerMax no longer seems to work on iOS7, and using it caused me to chase my tail for about 3 hours. I just discovered that when I use
NSUIntegerMax
,NSDateComponents
ignores set year. So for example this DOES NOT change the year:Whereas this DOES:
It may be an iOS7 bug or it may be that using NSUIntegerMax working was a fluke which no longer works. I will file a bug report and get a definitive answer.
Regardless, if you want to avoid unexpected consequences specify ALL the components else you might be chasing your tail!
Swift 2.0 版本如何将给定日期设置为上午 8 点
Swift 2.0 version of how you'd set a given date to 8am
应用此设置将时间从另一个日期设置为现有日期
Apply this to set the Time from an another date to an existing Date
这是一个更通用的 Swift (v2.1.1) 扩展,它基于 Andrew Schreiber 的有用答案。
Here's a more generic Swift (v2.1.1) extension that builds on Andrew Schreiber's helpful answer.
一个简单的例子。出于我的目的,我想获取明天中午 12 点左右的日期。
A swift example. For my purposes, I wanted to get the date for around 12 noon tomorrow.