我有两个字符串。
NSString *dateof = @"Mon May 21";
NSString *timeof = @"01.00 pm from 11.50 pm"; // 01.00 pm is the start time and 11.50 pm is the end time
我需要将这些保存为NSDate
s,格式为2012-05-21 13:00:00 +0000
.
到目前为止,我的方法是:
NSDate *currentTime = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents
*currentDateComps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:currentTime];
NSString *startDateStringWithYear = [NSString stringWithFormat:@"%@ %d", startDateString, currentDateComps.year];
NSString *endDateStringWithYear = [NSString stringWithFormat:@"%@ %d", endDateString, currentDateComps.year];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEE MM dd yyyy"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *startDate = [formatter dateFromString:startDateStringWithYear];
NSArray *timeDurationStringWords = [timeof componentsSeparatedByString:@" "];
// Calculate NSDate's for the start time for today:
NSString *startTimeString = [timeDurationStringWords objectAtIndex:0];
currentDateComps.hour = [[startTimeString substringToIndex:2] intValue];
currentDateComps.minute = [[startTimeString substringFromIndex:3] intValue];
if ([[timeDurationStringWords objectAtIndex:1] isEqualToString:@"pm"])
{
currentDateComps.hour += 12;
}
NSDate *startTime = [cal dateFromComponents:currentDateComps];
当我调试代码时,startTime
打印出2012-05-29 07:30:00 +0000
哪个不正确(日期和时间都不正确)。我认为这是因为格林威治标准时间。
我需要日期和时间2012-05-21 13:00:00 +0000
。