Mav*_*rik 2 iphone nsdate nsdateformatter ios
我基本上想要将特定日期(x)转换为前一天日期(x - 1天)以及下一天日期(x + 1天).我使用以下代码:
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
Run Code Online (Sandbox Code Playgroud)
但是我的日期(x)是NSString格式,我需要在应用上面的代码之前将NSString(myDateString)转换为NSDate(myDate).我有一个NSString包含日期格式MM-dd-yyyy.对于转换我使用以下代码,但我得到荒谬的价值观.
NSLog(@"myDateString=%@",myDateString);//output:myDateString=10-25-2012//all correct
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-yyyy"];
NSDate *myDate=[formatter dateFromString:myDateString];
NSLog(@"myDate=%@",myDate);//output:myDate=2012-10-24 18:30:00 +0000 // I only want the date to be shown // and why has the format changed
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
NSLog(@"datePlusOneDay=%@",datePlusOneDay);//output:datePlusOneDay=2012-10-25 18:30:00 +0000// I only want the date to come , not time // and why has the format changed
Run Code Online (Sandbox Code Playgroud)
稍后我需要将NSDate转换为NSString
NSString *curentString=[formatter stringFromDate:datePlusOneDay];
NSLog(@"curentString=%@",curentString); //output:curentString=10-26-2012
Run Code Online (Sandbox Code Playgroud)
同样,我也希望得到上一个日期.请帮帮我们!! 和ho ho MERRY CHRISTMAS !!
做到:componets.day = 1获得下一个,-1前一天.
NSDate *date = [NSDate date]; // your date from the server will go here.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
NSLog(@"newDate -> %@",newDate);
Run Code Online (Sandbox Code Playgroud)