我正在使用NSDateFormatter在iPhone应用程序中工作。正在从Web服务中获取时间,例如"00:00:00", "16:00:00","15:30:00" and so on
。我需要将这些时间转换为如果时间为"00:00:00" to "12 AM"
,则时间为"16:00:00" to "4 PM"
,如果时间为“ 15:30:00”至“ 3.30 PM”。我已经将以下代码用于此,但是当我通过"16:00:00" the date returns null
时。
NSString *dats1 = @"16:00:00";
NSDateFormatter *dateFormatter3 = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter3 setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter3 setDateFormat:@"hh:mm:ss"];
NSDate *date1 = [dateFormatter3 dateFromString:dats1];
NSLog(@"date1 : %@", date1); **// Here returning (null)**
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSLog(@"Current Date: %@", [formatter stringFromDate:date1]); **// Here also returning (null)**
[formatter release];
传递“ 00:00:00”时,它正确返回“ 12 AM”。谁能帮我解决这个问题?预先感谢。
NSString *dats1 = @"16:00:00";
NSDateFormatter *dateFormatter3 = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter3 setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter3 setDateFormat:@"HH:mm:ss"];
NSDate *date1 = [dateFormatter3 dateFromString:dats1];
NSLog(@"date1 : %@", date1); **// Here returning (null)**
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSLog(@"Current Date: %@", [formatter stringFromDate:date1]); **// Here also returning (null)**
[formatter release];
谢谢。
let timeFormatter = NSDateFormatter()
timeFormatter.dateStyle = .NoStyle
timeFormatter.timeStyle = .ShortStyle
timeFormatter.stringFromDate(NSDate())
哪个返回17:12
或5:12 PM
,具体取决于当前设备的语言环境。
NSDate
,然后再次格式化为NSString
, NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:dats1];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(@"%@",formattedDate);
对于Swift
let dateFormatter = NSDateFormatter()
//if some one want 12AM,5PM then use "hh mm a"
//if some one want 00AM,17PM then use "HH mm a"
dateFormatter.dateFormat = "hh mm a"
let stringDate = dateFormatter.stringFromDate(NSDate())
println(stringDate)
NSLocale *12hourFomrat = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
df.locale = 12hourFomrat;
此始终保持24小时格式
NSLocale *24hourFormat = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
df.locale = 24hourFormat
[dateFormatter3 setDateFormat:@"HH:mm:ss"];
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh mm a"
let formattedDate = dateFormatter.string(from: Date())