How to change nsstring to nsdate format in iphone?

半腔热情 提交于 2021-01-28 01:04:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!