2

I am writing a method that takes string and returns string. I am trying to use it in another method.

- (NSString*) formatDate:(NSString*) showStartDateTime
{
    NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"UTC"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:tz];
    [dateFormatter setDateFormat:@"EEE MM/dd/yyyy"];
    NSDate*dattt=[dateFormatter dateFromString:showStartDateTime ];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString*tempo2= [dateFormatter stringFromDate:dattt];
    return tempo2;

}

This is how I am using it. [self formatDate:@"Fri 08/08/2014"] is it a correct way to use it?

NSString *hellostring=[self formatDate:@"Fri 08/08/2014"];
NSLog(@"%@",hellostring);

I know it does not work. Any suggestion is appreciated.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Neprocker
  • 99
  • 8
  • Define "doesn't work". – rmaddy Jul 25 '14 at 01:37
  • I just ran it, and my console output is "2014-08-08" as expected. – danh Jul 25 '14 at 01:53
  • @danh I am trying to see if I can reuse this method to simply pass a string and get back to correct format. – Neprocker Jul 25 '14 at 01:57
  • @Neprocker please define "correct format". Maybe you should edit the question to say exactly what you hope the method will do. – danh Jul 25 '14 at 02:00
  • @danh The method pretty obviously is attempting to convert a NSString date from "EEE MM/dd/yyyy" to "yyyy-MM-dd" format. And it's getting bit by some flakiness in the date formatter in that if you try to parse a day-of-week value it often fails. As vikingosegundo indicates, this problem appears to be somehow interconnected with the [locale "feature"](http://stackoverflow.com/q/6613110/581994), but I prefer to deal with it by removing the day-of-week info before attempting to parse. – Hot Licks Jul 25 '14 at 02:45

1 Answers1

2

I wrote a command line app and wasnt able to get it running, as already dateFromString: resulted in nil, until I added dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

- (NSString*) formatDate:(NSString*) showStartDateTime
{
    NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"UTC"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:tz];

    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setDateFormat:@"EEE MM/dd/yyyy"];
    NSDate*dattt=[dateFormatter dateFromString:showStartDateTime ];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString*tempo2= [dateFormatter stringFromDate:dattt];
    return tempo2;

}

Now it returns 2014-08-08

see Technical Q&A QA1480: NSDateFormatter and Internet Dates

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178