昨天在Objective-c中获得NSDate

Dan*_*any 9 cocoa-touch objective-c nsdate

我需要使用NSDate对象获取昨天的日期.任何的想法?

编辑:解决:

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

Ila*_*ian 46

试试这个代码.通过这种方式,您可以获得下一天,下个月,前几天,前几个月..

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];
Run Code Online (Sandbox Code Playgroud)

  • +1这是一个更好的答案.如果今天或昨天是当地时间从夏令时变为标准时间(反之亦然)的日期,则根据您执行该操作的时间,添加或减去86400秒可以给出错误答案. (6认同)

das*_*dom 9

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(60.0f*60.0f*24.0f)];
Run Code Online (Sandbox Code Playgroud)

编辑:此解决方案不正确.请参阅Aadhiras的答案以获得正确的解决方案.