开发者

How to change NSDateFormatter for a string

I have a string which has date field in it. I am storing the field as NSString in my database like 2011-12-07 21:15:00 +0000.

I am using the following code to get the date from the string in the date format like :

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

I want the above date format in the time format as hh a but it always gives null. My code :

    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 setLoc开发者_如何学Pythonale:[[[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.

I am not sure what I am doing wrong here. Can anybody help me out here ?


Show the output when you run this code that would be helpful. But if I had to guess you are doing something wrong in the time format part. I would suggest you get your date from the database string, using the date formatter as you have it, and at this point in the code: (Which I am assuming works)

[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ];
NSDate *date1 = [dateFormat dateFromString:startSection];

NSLog(@"Date 1 : %@", date1);

Switch gears after the above code and do this instead too get your time in a string in the format desired:

[timeFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ];
NSString * time = [timeFormat stringWithDate:date1];
NSLog(@"Time 1 : %@", time);


Your date goes 2011-12-07 21:15:00 +0000 while your formatString goes @"yyyy-MM-dd HH:mm:ss.S". The ss.S is the problem here. Make it @"yyyy-MM-dd HH:mm:ss +S" and it'll work.

With regards to the time format, I am not sure what you are doing. You are obviously passing the same string to it (startSection) which doesn't even look close to hh a.

Update: Oh, and if I am not mistaking, the formatting follows this conventions which means that you are probably looking for Z and not for S.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜