我有以下代码。在这里,我尝试了两种方法来获取日期和时间。如果我使用格式化程序,它会给我上述错误。如果我不使用它,日期格式不正确加上我得到的时间也是不正确的。请帮助。
NSDate *pickupHoursLate;
NSDate *dropHoursLate;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
NSLog(@"Old Date and Time : %@",[formatter stringFromDate:[NSDate date]]);
这给我输出像 12-07-2016 18:32 我想要的
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
int pickHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:@"pickupPriorTimePeriod"] intValue];
[components setHour:pickHoursToAdd];
pickupHoursLate = [calender dateByAddingComponents:components toDate:[formatter stringFromDate:[NSDate date]] options:0];
此行为我提供错误
int dropHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dropPriorTimePeriod"] intValue];
[components setHour:dropHoursToAdd];
dropHoursLate = [calender dateByAddingComponents:components toDate:[NSDate date] options:0];
此行在我将当前时间加入2小时后给出了值 2016-07-12 15:02:51 +0000 ,但此处时间不正确
答案 0 :(得分:0)
试试这个......
NSDate *pickupHoursLate;
NSDate *dropHoursLate;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(@"Old Date and Time : %@",[formatter stringFromDate:[NSDate date]]); **<this give me output like this 12-07-2016 18:32 which I want>**
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
int pickHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:@"pickupPriorTimePeriod"] intValue];
[components setHour:pickHoursToAdd];
//Editing start
NSString *dateStr = [formatter stringFromDate:[NSDate date]] ;
NSDate *date = [formatter dateFromString:dateStr];
pickupHoursLate = [calender dateByAddingComponents:components toDate: date options:0]; **<This Line gives me the error>**
//Editing End
int dropHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dropPriorTimePeriod"] intValue];
[components setHour:dropHoursToAdd];
dropHoursLate = [calender dateByAddingComponents:components toDate:[NSDate date] options:0]; **<This Line gives me the value "2016-07-12 15:02:51 +0000" after adding 2 hrs to current time but here the time is incorrect>**