NSDate delay date change

僤鯓⒐⒋嵵緔 提交于 2019-12-02 08:44:37

问题


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!

Edit: 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]];

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.


回答1:


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]];

Subtract one day if necessary:

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];


来源:https://stackoverflow.com/questions/19754433/nsdate-delay-date-change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!