我花了几个小时试图完成这项工作。这就是我想要做的事情:
最后一点不起作用。它适用于诸如下午12:00和下午12:30之类的时间,但是对于诸如下午2:30之类的时间,它将按照预期在下午4:30而不是下午6:30输出。这是我的代码,分解为反映这三个任务。
任务1 - 检查文本输入是否为HH:mm AM / PM
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[format setTimeZone:[NSTimeZone systemTimeZone]];
[format setDateFormat:@"HH:mm a"];
NSString *dateString = textField.text;
NSLog(@"input datestring: %@", dateString);
NSDate *parsed = [format dateFromString:dateString];
if (parsed) {
NSLog(@"datestring is valid, %@", parsed);
}
任务2-更新该日期的m / d / y组件以反映今天的。
//gregorian calendar, get the hour and minute components from the input time
NSCalendar *greg = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [greg components: NSCalendarUnitHour | NSCalendarUnitMinute fromDate:parsed];
//get the month/day/year components from the current date
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
//set the components of the original date to the month/day/year components of today
[components setYear:comps.year];
[components setDay:comps.day];
[components setMonth:comps.month];
//create the new date.
NSDate* newDate = [greg dateFromComponents:components];
NSLog(@"########### %@", newDate);
任务3 - 增加4小时。
int hours = 4 ;
NSString *output;
NSDateComponents *add = [[NSDateComponents alloc] init];
[add setHour:hours];
newDate = [greg dateByAddingComponents:add toDate:newDate options:0];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterShortStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
output = [df stringFromDate:newDate];
NSLog(@"new date: %@", output);
记录:
2015-08-27 16:03:35.672 Del Taco[1960:117431] input datestring: 2:30 pm
2015-08-27 16:03:35.673 Del Taco[1960:117431] datestring is valid, 2000-01-01 20:30:00 +0000
2015-08-27 16:03:35.673 Del Taco[1960:117431] ########### 2015-08-27 19:30:00 +0000
2015-08-27 16:03:35.674 Del Taco[1960:117431] new date: 8/27/15, 4:30 PM
答案 0 :(得分:1)
我想我已经弄明白了。这是我的日期格式化程序,我在其中设置如下格式:
@"HH:mm a"
我去Unicode's网站仔细检查我是否正确行事,最后将格式字符串更改为:
@"h:mm a"
事情似乎很顺利!