问题
I have struggling with to convert nsstring to nsdate format. I have a date in nsstring format like (2011-08-25 18:30:00 +0000), but i want to change it in nsdate format (08/26/2011). How to change it? Can any one help me please? Thanks in advance... I have spend one day to solve this but i cant find out the solution.. Please help me friends....
This is my code,
NSString *dateString = @"2011-08-25 18:30:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"Converted date is %@",dateFromString);
Output is,
Converted date is (null)
Yuva.M
回答1:
NSString *dateWithInitialFormat = @"2011-08-25 18:30:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateWithInitialFormat];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date];
NSLog(@"dateWithNewFormat: %@", dateWithNewFormat);
From NSLog: dateWithNewFormat: 08/25/2011
See Date Format Patterns
回答2:
You need to use an NSDateFormatter and set the date format to match how you're storing it, like the below.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *myDate = [df dateFromString: myDateString];
回答3:
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMMM dd, yyyy"];
NSDate* d = [df dateFromString:@"January 06, 1992"];
NSLog(@"%@", d);
NSDate *dispalyDate = d;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd MMM"];
NSString *str = [dateFormat stringFromDate:dispalyDate];
NSLog(@"%@", str);
来源:https://stackoverflow.com/questions/7204748/how-to-change-nsstring-to-nsdate-format-in-iphone