简体   繁体   中英

NSDateFormatter Does not convert correctly

I have a NSString which is passed from an xml feed........

NSString *strDate =@"Thu, 22 Apr 2010 10.30 am CEST";

I'm currently using this code to format the date........

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm a vvvv"];
    NSDate *myDate = [dateFormatter dateFromString:date];
    [dateFormatter setDateFormat:@"HH"];
    NSLog(@"%@", [dateFormatter stringFromDate:myDate]);

I want to format my string only to display only hours and currently I'm getting value like this.

strDate =@"2010-04-10 14:00:00 +0530";

Can anyone please help me with this?......


I'm sorry.It's my mistake.It should be like this.

NSString *strDate =@"Thu, 22 Apr 2010 10:30 am CEST";

What my requirement is to get hour part only from above string using NSDateFormatter. How can I achieve that. Sorry for the earlier mistake.

Thanks.

If you want to get the 10 of 10:30 (if its ur requirement) then you can do it like:

strDate = @"Thu, 22 Apr 2010 10:30 am CEST";
NSArray *dateComponents = [strDate componentsSeparatedByString:@" "];
NSString *requiredString = [dateComponents objectAtIndex:4];
dateComponents = [requiredString componentsSeparatedByString:@":"];
requiredString = [dateComponents objectAtIndex:0];

and when you do:

NSLog(rquiredString);

Output : 10;

This is just a workaround, for better approach you should go through the NSDateComponents class.

Hope this helps.

Thanks,

Madhup

You want to do this:

NSString *strDate =@"Thu, 22 Apr 2010 10:30 am CEST";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm a"];
NSDate *myDate = [dateFormatter dateFromString:strDate];
[dateFormatter setDateFormat:@"hh"];
strDate = [dateFormatter stringFromDate:myDate];
NSLog(@"%@", strDate);

(Firstly your original formatter was wrong, you had a: instead of a .) EDIT no longer the case

Secondly, you want to ignore the CEST bit as this will cause your timezone being changed

change to

[dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh.mm a vvvv"];

(. instead of : in hh:mm)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM