NSDate延迟日期更改 [英] NSDate delay date change

查看:122
本文介绍了NSDate延迟日期更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的解决方案,但是有谁知道如何延迟NSDate在午夜过后的变化?任何见解都会非常有用,谢谢!

This is probably a simple solution but does anyone know how to delay the NSDate change past midnight? Any insight would be really helpful, thanks!

编辑:
我目前正在以这种方式获取日期并显示位置数据基于那一天。但是,就像NSDate在逻辑上应该工作一样,它会在午夜切换到第二天。我希望日期在凌晨3点而不是在凌晨12点更改。

I am currently getting the date this way and displaying a locations data based on that day. But, much like the NSDate is logically supposed to work, it switches to the next day at midnight. I want the date to change at 3am instead of at 12am.

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"EEEE"];
today = [f stringFromDate:[NSDate date]];

我应该使用时间而不是使用NSDate吗?我对iOS来说是一个菜鸟,所以任何见解都会有所帮助。感谢您的回复。

Should I just use the time instead of using NSDate? I am a bit of a noob to iOS so any insight would be helpful. Thanks for your responses already.

推荐答案

我必须承认我还不明白为什么你想要的显示错误的工作日
名称,但以下代码应该做你想要的。这只是
实现任务的各种方式之一。

I must admit that I do not yet understand why you want to display a "wrong" weekday name, but the following code should do what you want. This is only one of various ways to achieve your task.

将日期转换为日期组件:

Convert date to "date components:"

NSCalendar *cal = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *comp = [cal components:unitFlags fromDate:[NSDate date]];

如有必要减去一天:

if (comp.hour < 3) {
    comp.day -= 1;
}

将调整后的组件转换回日期:

Convert adjusted components back to date:

NSDate *adjustedDate = [cal dateFromComponents:comp];

您的原始代码,现在使用调整后的日期:

Your original code, now using the adjusted date:

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"EEEE"];
NSString *today = [f stringFromDate:adjustedDate];

这篇关于NSDate延迟日期更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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