Question

I know this will be a silly question, but I tried everything and still couldn't achieve what I wanted to do.

This is my question:

I want to check two time values and a date, I have string which is having time like this "05.30 AM". I want to convert it into time format [it is better if i can convert exactly the way it is now]. I know there is a way which can compare two time values using:

NSComparisonResult result = [date1 compare:date2];.

I have followed below code to convert my string value to the time format but it is only returns null.

Please guide me for this issue:

NSString* tim = @"11:12 AM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];

NSDate *formatedTime= [formatter dateFromString:tim];
NSLog(@"TIME : %@",formatedTime);
Was it helpful?

Solution

For this particular case (with tim formatted the way you have it) you just missing one line: [formatter setDateStyle:NSDateFormatterNoStyle]; this will tell formatter not to look for date in your string.

NSString* tim = @"11:12 AM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateStyle:NSDateFormatterNoStyle];

NSDate *formatedTime= [formatter dateFromString:tim];
NSLog(@"TIME : %@",formatedTime);

OTHER TIPS

You need set the format.

[formatter setDateFormat:@"hh:mm a"];
NSString* tim = @"11:12 AM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm a"];

NSDate *formatedTime= [formatter dateFromString:tim];
NSLog(@"TIME : %@",formatedTime);

But you will receive

TIME : 1999-12-31 23:12:00 +0000

since year is unknown.

First you need to format your String like this

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss ZZZ";
[formatter dateFromString:@"Fri, 25 Jan 2014 5:30:22 +0000"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top