简体   繁体   中英

How to change nsstring to nsdate format in iphone?

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

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

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];
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM