Obtain yesterday with NSDate in objective-c

只谈情不闲聊 提交于 2019-12-04 19:11:31

问题


I need to obtain the date of yesterday with NSDate object. Any idea?

EDIT : SOLVED:

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400];


回答1:


NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(60.0f*60.0f*24.0f)];

Edit: This solution isn't correct. See Aadhiras answer for the correct solution.




回答2:


Try this code. With this way, you can get next days, next months, previous days , previous months..

NSDate *now = [NSDate date];
int daysToAdd = -1;  

// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];

// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDate *yesterday = [gregorian dateByAddingComponents:components toDate:now options:0];
NSLog(@"Yesterday: %@", yesterday);
[gregorian release];


来源:https://stackoverflow.com/questions/8135382/obtain-yesterday-with-nsdate-in-objective-c

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