我正试图从以下字符串中获取时间和24小时格式:
2015年7月2日下午2:30:00
这就是我的尝试:
-(NSString*)returnDate:(NSString*)dateString
{
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"MM/dd/yyyy hh:mm:ss aaa"];
NSDate *date = [dateFormatter1 dateFromString:dateString];
dateString = [date descriptionWithLocale:[NSLocale systemLocale]];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"HH:mm a"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateString = [dateFormatters stringFromDate: destinationDate];
return dateString;
}
输出:4:30
这是以12小时格式返回正确的时间。我想要24小时格式的时间。
所需输出:16:30
答案 0 :(得分:4)
问题中有很多代码,试试这个:
NSString *dateString = @"7/2/2015 4:30:00 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss aaa"];
NSDate *date = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:@"HH:mm"];
dateString = [dateFormatter stringFromDate: date];
NSLog(@"dateString: %@", dateString);
输出:
dateString:16:30