Reputation: 345
In my app I am using the date format like 'Thurs 10th April'
. But I am getting the date format like 'Thurs 10 April'
.I don't know how to change the format for this.
For First of January- It should come like 'Jan 1st'
.
For Second of August -It should come like 'Aug 2nd
'.
For Third of April -It should come like 'April 3rd'
.
I want the date in this format. I am new to Xcode. Please can anyone help to solve this.
Upvotes: 1
Views: 520
Reputation: 3790
Here is what you can do:
Divide the string into components and store them in array.
Fetch the day part from that array and do some checking on it.
Append appropriate day suffix to that day.
Finally append entire string.
Below is the code:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"EEE dd MMMM"];
NSDate *now = [NSDate date];
NSString *dateString = [format stringFromDate:now];
NSArray*tempString1 = [dateString componentsSeparatedByString:@" "];
NSMutableString *tempDate = [[NSMutableString alloc]initWithString:[tempString1 objectAtIndex:1]];
int day = [[tempString1 objectAtIndex:1] intValue];
NSLog(@"%d",day);
switch (day) {
case 1:
case 21:
case 31:
[tempDate appendString:@"st"];
break;
case 2:
case 22:
[tempDate appendString:@"nd"];
break;
case 3:
case 23:
[tempDate appendString:@"rd"];
break;
default:
[tempDate appendString:@"th"];
break;
}
NSLog(@"%@",tempDate);
NSString *str1 = [[tempString1 objectAtIndex:0] stringByAppendingString:@" "];
NSString *str2 = [str1 stringByAppendingString:tempDate];
NSString *str3 = [str2 stringByAppendingString:@" "];
NSString *finalDate = [str3 stringByAppendingString:[tempString1 objectAtIndex:2]];
NSLog(@"%@",finalDate);
Upvotes: 1
Reputation: 623
I am assuming that you have your date ready to be used in mutable string. If So, you can use the following to get the output you wanted.
NSMutableString *mutableStrDate = // Your date in Mutable String Format.
int day = [[mutableStrDate substringFromIndex:[mutableStrDate length] - 2] intValue];
switch (day)
{
case 1:
case 21:
case 31:
[mutableStrDate appendString:@"st"];
break;
case 2:
case 22:
[mutableStrDate appendString:@"nd"];
break;
case 3:
case 23:
[mutableStrDate appendString:@"rd"];
break;
default:
[mutableStrDate appendString:@"th"];
break;
}
NSLog(@"Formatted Date with %@",mutableStrDate);
Hope this helps.
Upvotes: 2
Reputation: 12782
Have a look at the lovely, if complicated, NSDateFormatter class. While you are there, meet her friends, NSLocale, NSTimeZone, NSCalendar, NSDate, and NSDateComponents. Also be sure to read the Date & Time Programming guide from Apple (and read it again.)
Upvotes: 2