converting date to correct format

后端 未结 2 1755
温柔的废话
温柔的废话 2021-01-23 18:57

I\'ve a webservice which gives back my date in the following way.

Wed Oct 31 11:59:44 +0000 2012

But I want it to give it back in this way

相关标签:
2条回答
  • 2021-01-23 19:36

    There are a few issues with your format string for parsing the original date. And the locale isn't set properly. There is no need to set the timezone. That will be processed from the supplied date/time string.

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [f setLocale:posix];
    [f setDateFormat:@"EEE MMM dd hh:mm:ss Z yyyy"];
    NSDate *date = [f dateFromString:@"Wed Oct 31 11:59:44 +0000 2012"];
    

    You want to use the en_US_POSIX locale whenever you are parsing (or formatting) a fixed format date that is not from or for a user. Do not use the en_US_POSIX locale to display dates or times to a user.

    0 讨论(0)
  • 2021-01-23 19:47

    Step 1: create an NSDateFormatter to convert your string from server to an NSDate object by setting the format to the format of the "server string"

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"E MMM d hh:mm:ss Z y"];
    NSDate *date = [f dateFromString:@"Wed Oct 31 11:59:44 +0000 2012"];
    

    Step 2: create another NSDateFormatter with the desired output string and convert your new NSDate object to a string object using the new NSDateFormatter

    NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
    [f2 setDateFormat:@"dd-MM-y hh:mm"];
    [f2 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSString *s = [f2 stringFromDate:date];
    
    desiredformat = s;
    

    P.S. I'm not sure of f format, check this link http://www.developers-life.com/nsdateformatter-and-uifont.html

    0 讨论(0)
提交回复
热议问题