0
votes

I have a date with the format: Fri Jul 16 16:58:46 +0000 2010. To convert it to Fri Jul 16 2010 I tried:

NSDateFormatter *df = [[NSDateFormatter alloc] init];

for(int i=0; i<[self.data count]; i++) {
    id celldata = [self.data objectAtIndex:i];
    NSString *str = [NSString stringWithFormat:@"%@", [celldata objectForKey:@"created_at"]];
    NSLog(@"date for %u is %@",i, str); //this works and writes the date
    [df setDateFormat:@"eee MMM dd HH:mm:ss Z yyyy"];
    NSDate *date = [df dateFromString:str];
    [df setDateFormat:@"eee MMM dd yyyy"];
    NSString *dateStr = [df stringFromDate:date];
    NSLog(@"%@",dateStr);
}

But NSLog(@"%@",dateStr) only writes (null). How to get it working?

EDIT For whatever reason I got it working by changing

[df setDateFormat:@"eee MMM dd HH:mm:ss Z yyyy"];

to

[df setDateFormat:@"MMM dd HH:mm:ss Z yyyy"];

and deleting the week day from my string. However, thank you all.

3
It's probably failed to parse the string into your variable date. Try doing NSLog(@"%@", date) and see if that's nil. - joerick
@sch: "date for 0 is Sun Apr 29 11:11:22 +0000 2012" and so on - Alexander Meiler
There's no way that that second sequence works, since the first date format is a total mismatch for the incoming string. - Hot Licks
And you could be getting bit by the 12/24 "feechure" -- check the phone Settings to be sure that the 12/24 switch matches your locale (12 for the US, 24 for most everywhere else). - Hot Licks
(And just out of curiosity, where did you copy this code from? Someone else was having similar problems with VERY similar data -- both of you have the extraneous/useless stringWithFormat call -- so I'm guessing you're using the same original source.) - Hot Licks

3 Answers

0
votes

This might help you out a bit. I had a similar problem a while back, so I created the following methods.


Definitions

#define DATE_TYPE_hhmmss [NSArray arrayWithObjects:@"h", @"m", @"s", nil]
#define DATE_TYPE_MMDDYYYY [NSArray arrayWithObjects:@"M", @"D", @"Y", nil]
#define DATE_TYPE_MMDDYYYYhhmmss [NSArray arrayWithObjects:@"M", @"D", @"Y", @"h", @"m", @"s", nil]
#define DATE_TYPE_MMDDYYYYWWhhmmss [NSArray arrayWithObjects:@"M", @"D", @"Y", @"W", @"h", @"m", @"s", nil]
#define DATE_TYPE_MMDDYYYYhhmmssWW [NSArray arrayWithObjects:@"M", @"D", @"Y", @"h", @"m", @"s", @"W", nil]
#define DATE_TYPE_YYYYMMDD [NSArray arrayWithObjects:@"Y", @"M", @"D", nil]
#define DATE_TYPE_YYYYMMDDhhmmss [NSArray arrayWithObjects:@"Y", @"M", @"D", @"h", @"m", @"s", nil]
#define DATE_TYPE_YYYYMMDDWWhhmmss [NSArray arrayWithObjects:@"Y", @"M", @"D", @"W", @"h", @"m", @"s", nil]
#define DATE_TYPE_YYYYMMDDhhmmssWW [NSArray arrayWithObjects:@"Y", @"M", @"D", @"h", @"m", @"s", @"W", nil]
#define DATE_TYPE_FRIENDLY [NSArray arrayWithObjects:@"xx", nil]

Date Methods

Create Date From Values

-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year {
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];

    [dateFormatter setDateFormat:@"MM"];
    [dateComponents setMonth:month];
    [dateFormatter setDateFormat:@"DD"];
    [dateComponents setDay:day];
    [dateFormatter setDateFormat:@"YYYY"];
    [dateComponents setYear:year];

    NSDate * result = [calendar dateFromComponents:dateComponents];

    return result;
}

-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute {
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]];

    [dateFormatter setDateFormat:@"MM"];
    [dateComponents setMonth:month];
    [dateFormatter setDateFormat:@"DD"];
    [dateComponents setDay:day];
    [dateFormatter setDateFormat:@"YYYY"];
    [dateComponents setYear:year];
    [dateFormatter setDateFormat:@"HH"];
    [dateComponents setHour:hour];
    [dateFormatter setDateFormat:@"MM"];
    [dateComponents setMinute:minute];

    NSDate * result = [calendar dateFromComponents:dateComponents];

    return result;
}

-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute second:(int)second {
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];

    [dateFormatter setDateFormat:@"MM"];
    [dateComponents setMonth:month];
    [dateFormatter setDateFormat:@"DD"];
    [dateComponents setDay:day];
    [dateFormatter setDateFormat:@"YYYY"];
    [dateComponents setYear:year];
    [dateFormatter setDateFormat:@"HH"];
    [dateComponents setHour:hour];
    [dateFormatter setDateFormat:@"MM"];
    [dateComponents setMinute:minute];
    [dateFormatter setDateFormat:@"SS"];
    [dateComponents setSecond:second];

    NSDate * result = [calendar dateFromComponents:dateComponents];

    return result;
}

Get String From Date

-(NSString *) getStringFromDate:(NSDate *)date dateType:(NSArray *)dateType {
    NSString * result = @"";

    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSString * format = @"";

    NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];

    NSInteger year = [dateComponents year];
    NSInteger month = [dateComponents month];
    NSInteger day = [dateComponents day];
    NSInteger weekday = [dateComponents weekday];
    NSInteger hour = [dateComponents hour];
    NSInteger minute = [dateComponents minute];
    NSInteger second = [dateComponents second];

    if (dateType != nil) {
        for (int x = 0; x < [dateType count]; x++) {
            if (x == ([dateType count]-1)) {
                if ([[dateType objectAtIndex:x] isEqualToString:@"Y"]) {
                    format = [format stringByAppendingFormat:@"%d", year];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"M"]) {
                    format = [format stringByAppendingFormat:@"%d", month];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"D"]) {
                    format = [format stringByAppendingFormat:@"%d", day];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"W"]) {
                    format = [format stringByAppendingFormat:@"%d", weekday];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"h"]) {
                    format = [format stringByAppendingFormat:@"%d", hour];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"m"]) {
                    format = [format stringByAppendingFormat:@"%d", minute];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"s"]) {
                    format = [format stringByAppendingFormat:@"%d", second];
                }
            } else {
                if ([[dateType objectAtIndex:x] isEqualToString:@"Y"]) {
                    format = [format stringByAppendingFormat:@"%d|", year];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"M"]) {
                    format = [format stringByAppendingFormat:@"%d|", month];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"D"]) {
                    format = [format stringByAppendingFormat:@"%d|", day];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"W"]) {
                    format = [format stringByAppendingFormat:@"%d|", weekday];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"h"]) {
                    format = [format stringByAppendingFormat:@"%d|", hour];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"m"]) {
                    format = [format stringByAppendingFormat:@"%d|", minute];
                } else if ([[dateType objectAtIndex:x] isEqualToString:@"s"]) {
                    format = [format stringByAppendingFormat:@"%d|", second];
                }
            }

            if ([[dateType objectAtIndex:x] isEqualToString:@"xx"]) {
                format = [NSString stringWithFormat:@"Year: %d, Month: %d, Day: %d, Weekday: %d, Hour: %d, Minute: %d, Second: %d", year, month, day, weekday, hour, minute, second];
            }
        }
    } else {
        format = [format stringByAppendingFormat:@"%d|", year];
        format = [format stringByAppendingFormat:@"%d|", month];
        format = [format stringByAppendingFormat:@"%d|", day];
        format = [format stringByAppendingFormat:@"%d|", weekday];
        format = [format stringByAppendingFormat:@"%d|", hour];
        format = [format stringByAppendingFormat:@"%d|", minute];
        format = [format stringByAppendingFormat:@"%d|", second];

        format = [NSString stringWithFormat:@"%d|%d|%d|%d|%d|%d|%d", year, month, day, weekday, hour, minute, second];
    }

    result = format;

    return result;
}

Example

NSDate * date = [self getDateWithMonth:12 day:24 year:1994];
NSString * dateInString = [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY];

int month = [[[dateInString componentsSeparatedByString:@"|"] objectAtIndex:0] intValue];
int day = [[[dateInString componentsSeparatedByString:@"|"] objectAtIndex:1] intValue];
int year = [[[dateInString componentsSeparatedByString:@"|"] objectAtIndex:2] intValue];

NSLog(@"String of Date: \"%@\"", dateInString);
NSLog(@"Month: %d", month);
NSLog(@"Day: %d", day);
NSLog(@"Year: %d", year);

The method [self getDateWithMonth:12 day:24 year:1994] returns an NSDate object which is usually hard to read, so you can use [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY] to get a string of an NSDate object.

Use the definitions (macros) to specify the format of the date you would like to get in the string.

For example: DATE_TYPE_hhmmss would return the Hour|Minute|Second, DATE_TYPE_MMDDYYYY would return the Month|Day|Year, DATE_TYPE_MMDDYYYYhhmmss would return the Month|Day|Year|Hour|Minute|Second, DATE_TYPE_MMDDYYYYWWhhmmss would return the Month|Day|Year|Weekday (#)|Hour|Minute|Second

and so on...

Console Log

2012-04-29 13:42:15.791 Atomic Class[1373:f803] String of Date: "12|24|1994"
2012-04-29 13:42:15.793 Atomic Class[1373:f803] Month: 12
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Day: 24
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Year: 1994
0
votes

If the original strings you are parsing to dates are really in the format of "20081122" then the first call to "setDateFormat" is incorrect in both snippets, as the format of the specified is incorrect.

Assuming that [celldata objectForKey:@"created_at"] is returning dates in the format of "20081122" per your second code snippet, you need to change the first call to setDateFormat to use the correct format for the string, "yyyyMMdd" This will drive a correct conversion when you call the method "dateFromString" Then, once you have a NSDate* object representation, you can use whatever format you need when you convert it back to a string via stringFromDate.

NSString *dateStr = @"20081122";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//This is the important change here, this format MUST match the format of the string.
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];  
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];  
[dateFormat release];
0
votes

Use Dateformatter for week EEE instead of eee

[df setDateFormat:@"EEE MMM dd HH:mm:ss Z yyyy"];

I hope this will be helpful to you...