2

我必须将给定的时间转换为 24 小时格式。但我没有得到它。不知道我哪里出错了。如果我将 TimeStart 设置为下午 1:15,那么我应该得到 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。我该如何解决?

4

3 回答 3

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);
于 2012-10-23T05:09:39.607 回答
1

我只是简单地 setDateFormat 像[formatter setDateFormat:@"HH:mm"]; Removea

并在 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"));
于 2012-10-23T04:59:40.530 回答
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

于 2012-10-23T05:11:12.617 回答