2011-10-14 51 views
0

我有一个字符串,其中有日期字段。我将字段作为NSString存储在我的数据库中,如2011-12-07 21:15:00 +0000。如何更改字符串的NSDateFormatter

我使用下面的代码,以获得从日期格式字符串的日期,如:

NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"]; 

我想在时间格式为hh一个上述日期格式,但它总是给空。 我的代码:

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

嘿!你试过我的建议吗?对你起作用吗? – Phlibbo

+0

嗨Phlibbo.Thanks你的帮助。但我的看法不仅仅是看日期。我必须对我必须编写代码的字符串进行排序。 – lifemoveson

+0

对不起,但我不明白你的最后一条评论的一个字:/ – Phlibbo

回答

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); 
+0

我相信我可以做到这一点,并在NSString中获得timeFormat的价值。但我担心的是,当我在nsstring上排序日期时会给出错误的输出。因此,我期待改变它NSDate,使日期的排序是正确的。 – lifemoveson

+0

根据我上面创建的处理字符串进行排序,或者将您的排序设置为您希望使用NSDate排序的内容。日期是日期,日期格式对NSDate没有影响。我无法猜测你的排序是什么意思,但就日期而言,我认为升序和降序将是唯一有意义的方法,因此您不需要执行任何格式化。如果您希望单独按小时排序,请在格式化后使用该字符串。 – EricLeaf

+0

我已经将小时单独用作字符串,然后添加到数组中,发现它在运行查询时排序不正确。我得到以下输出:Array:{10AM, 11AM, 8AM}如何更改以下数组排序?我目前正在使用sortedArrayUsingSelector:@selector(compare :)。 – lifemoveson

0

您的日期去2011-12-07 21:15:00 +0000,而你的formatString的推移@"yyyy-MM-dd HH:mm:ss.S"ss.S是这里的问题。使它@"yyyy-MM-dd HH:mm:ss +S",它会工作。

关于时间格式,我不确定你在做什么。你显然将相同的字符串传递给它(startSection),它甚至不会接近hh a

更新:哦,如果我没有弄错,格式如下this conventions这意味着你可能寻找Z和不S.