views:

154

answers:

4

Hi,

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?......

A: 

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

pheelicks
Hi,I'm sorry.It's my mistake.It should be like this.NSString *strDate =@"Thu, 22 Apr 2010 10:30 am CEST";
deamonsarea
What my requirement is to get hour part only from above string using NSDateFormatter. How can I achieve that. Sorry for the earlier mistake.
deamonsarea
My code DOES get the hour part. Have you even tried it?
pheelicks
A: 

change to

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

(. instead of : in hh:mm)

mihirpmehta
Hi,I'm sorry.It's my mistake.It should be like this.NSString *strDate =@"Thu, 22 Apr 2010 10:30 am CEST";
deamonsarea
What my requirement is to get hour part only from above string using NSDateFormatter. How can I achieve that. Sorry for the earlier mistake.
deamonsarea
A: 

Hi,

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.

deamonsarea
+1  A: 

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

Madhup