如何在iPhone中以24小时格式转换时间?

时间:2012-10-23 04:56:18

标签: iphone xcode

我必须以24小时格式转换给定时间。但我没有得到它。不知道我哪里出错了。  如果我在下午1:15有TimeStart那么我应该得到13:15 ..

Item *item=[sectionItems objectAtIndex:itemId];
 NSLog(@"%@",item.TimeStart);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm a"];
    NSString *formattedDateString = [dateFormatter stringFromDate:item.TimeStart];
    NSLog(@"%@",formattedDateString);

在上面的代码中,我有一个Item类,我有NSString * TimeStart; 当我看到formattedDateString时,它返回null。我该如何修复它?

3 个答案:

答案 0 :(得分:6)

 Item *item=[sectionItems objectAtIndex:itemId];
  NSLog(@"%@",item.TimeStart);

NSString *str = @"1:45.PM";// put here item.TimeStart

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"hh:mm.a"];// here give the format which you get in TimeStart

NSDate *date = [dateFormatter dateFromString: str];

dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"HH:mm"];

NSString *convertedString = [dateFormatter stringFromDate:date];
NSLog(@"Converted String : %@",convertedString);

答案 1 :(得分:1)

我只需像[formatter setDateFormat:@"HH:mm"];一样设置日期格式,删除a

用于检查甲酸盐时间的

和以下caode是24小时或12小时

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
[formatter release];
NSLog(@"%@\n",(is24h ? @"YES" : @"NO"));

答案 2 :(得分:0)

使用此选项设置24小时格式。

[currentDate setDateFormat:@"yyyy-MM-dd HH:mm"];

[formatter setDateFormat:@"HH:mm"];

不使用格式化程序

NSRange range;
range.location = 2;
range.length = 2;
NSString *dateString=[NSString stringWithFormat:@"%@:%@",[myString substringToIndex:2],          [myString substringWithRange:range]];

这是我在我的项目中使用的代码,它为我工作

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"HH:mm"];
 NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];

NSLog(@"Current time date:%@", dateString);

输出:当前时间日期:14:41