我有一个字符串,里面有日期字段。我将字段存储为我的数据库中的NSString,如2011-12-07 21:15:00 +0000。
我使用以下代码从日期格式的字符串中获取日期,如:
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];
我想要时间格式的上述日期格式为hh a但它始终为null。 我的代码:
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];
NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease];
[timeFormat setDateFormat:@"hh a"];
[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ];
NSDate *date1 = [dateFormat dateFromString:startSection];
NSLog(@"Date 1 : %@", date1);
[timeFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ];
NSDate *time1 = [timeFormat dateFromString:startSection];
NSString *strSection2 = [NSString stringWithFormat:@"%@", time1];
NSLog(@"Time 1 : %@", strSection2); /// always null at this place.
我不确定我在这里做错了什么。有人可以帮帮我吗?
答案 0 :(得分:0)
运行此代码时显示输出会有所帮助。但是,如果我不得不猜测你在时间格式部分做错了什么。我建议你从数据库字符串中获取日期,使用日期格式化程序,并在代码中的这一点: (我假设作品)
[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ];
NSDate *date1 = [dateFormat dateFromString:startSection];
NSLog(@"Date 1 : %@", date1);
在上述代码之后切换齿轮并执行此操作,而不是按照所需格式在字符串中获取时间:
[timeFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ];
NSString * time = [timeFormat stringWithDate:date1];
NSLog(@"Time 1 : %@", time);
答案 1 :(得分:0)
当您的formatString为2011-12-07 21:15:00 +0000
时,您的日期为@"yyyy-MM-dd HH:mm:ss.S"
。 ss.S
是问题所在。设为@"yyyy-MM-dd HH:mm:ss +S"
并且它会正常工作。
关于时间格式,我不确定你在做什么。您显然是将相同的字符串传递给它(startSection
),它甚至看起来都不接近hh a
。
更新:哦,如果我没有误会,格式化遵循this conventions,这意味着您可能正在寻找Z而不是S.