如何设置 NSDate 上的时间?
我想用我想要的小时:分钟:秒设置 NSDate 时间 目前我正在使用 NSDate 组件,但它没有给出期望的结果
[comps setHour: -hours];
[comps setMinute:0];
[comps setSecond:0];
NSDate *minDate = [calendar_c dateFromComponents:comps];
I want to set the NSDate time with my desired hours:minutes:seconds
currently im working with NSDate component but it is not giving the desired result
[comps setHour: -hours];
[comps setMinute:0];
[comps setSecond:0];
NSDate *minDate = [calendar_c dateFromComponents:comps];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这非常适合作为
NSDate
类别。对于上述类别,如果您想要更改现有日期的时间,则可以这样做:
NSDate *newDate = [someDate dateWithHour:10 分钟:30 秒:00];
如果但是,您尝试在现有日期中添加或减去小时数,执行此操作的类别方法也很简单:
This works great as an
NSDate
category.With the above category, if you have an existing date you want to change the time on, you do so like this:
NSDate *newDate = [someDate dateWithHour:10 minute:30 second:00];
If, however, you are trying to add or subtract hours from an existing date, a category method to do that is also straightforward:
你的方法应该可以正常工作。我需要解决此类问题(设置单独的日期组件),并且以下代码按我的预期工作。我的情况:我想创建一个使用当前日期的日期对象,但将时间设置为作为字符串传入的值。
需要注意的一件事是,当您判断时间是否准确时,您确实必须注意时区。例如,在我的应用程序中,当您在断点处停止时,您将看到 GMT 时间(因此它看起来与输入时间不同,输入时间是我的当地时间),但是当时间实际显示在屏幕上时应用程序,它正在被格式化以在本地时区中显示。您可能需要考虑这一点,以确定结果是否实际上与您的预期不同。
如果这没有帮助,你能详细说明“没有给出预期的结果”吗?它给出了什么结果?与您的预期相比如何?
Your approach should work fine. I needed a solution for this type problem (setting the individual date components) and the following code works as expected for me. My situation: I wanted to create a date object that used the current date but had the time set to a value that was passed in as a string.
One thing to note is that you really have to pay attention to time zones when you are judging whether a time appears to be accurate. For example, in my app, when you stop at a breakpoint, you will see the time in GMT (so it looks different than the input time, which is in my local time), but when the time is actually displayed on screen in the app, it is being formatted to display in the local timezone. You may need to take this into consideration to determine whether the result is actually different from what you would expect.
If this does not help, can you elaborate on "not giving the desired result"? What result is it giving and how does that compare to what you expected?
是 Swift2
is Swift2
Swift 5 解决方案(基于 @dattk 答案)适合那些担心弃用警告的人:)
Swift 5 solution (based on @dattk answer) for those who fear Deprecation warnings :)