I want to convert date 2012-12-26
to december 26, 2012
in iOS?
I am using websrvice and the data comes in this format 1990-12-26
.
I want to change this to december 26, 2012
format.
This is what I am doing:
lbl_Rightside.text = [rootElement stringValueForNode:@"date"];
NSLog(@"lbl_Rightside is %@",lbl_Rightside.text);
[lbl_Rightside release];
Getting date to this label on 1990-12-26
. Now I want to change date to december 26, 2012
format.
Any hints from experts would be very welcome.
you can use NSDateFormatter to do this kind of things. First
- convert your date String to a date object using dateFromString:
method.
- from date convert to string you want using stringFromDate: method
Different format strings can be found here.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *orignalDate = [dateFormatter dateFromString:YOUR_ORIGINAL_STRING];
[dateFormatter setDateFormat:@"MMMM dd, yyyy"];
NSString *finalString = [dateFormatter stringFromDate:orignalDate];
[dateFormatter release]; //if not using ARC
Check the official Apple documentation about NSDateFormatter. You should use this class to do this kind of formatting.
by using NSDateFormatter
NSString to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
NSDate convert to NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);
[dateFormatter release];
Try to look at NSDateFormatter Class,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; // this is your input date format
NSDate *newDate = [dateFormatter dateFromString:dateString];//converting string to date object
The format you are looking for is something like:
[dateFormatter setDateFormat:@"MMM dd,yyy"]; // setting new format
NSLog(@"The date is = %@",[dateFormatter stringFromDate:newDate])