converting date to correct format

て烟熏妆下的殇ゞ 提交于 2020-01-11 11:54:07

问题


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

31-10-2012 11:59

I know that it should be done with a NSDateFormatter. But I don't now how to implement it in the correct way.

I've something like this.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0:00"]];
    NSDate *date = [dateFormatter dateFromString:[genkInfo objectForKey:DATE]];

Can anybody help me?

Kind regards.

Code at the moment

  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"];
    NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
    [f2 setDateFormat:@"dd-MM-y hh:mm"];
    [f2 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSString *date2 = [f2 stringFromDate:date];

Webservice layout

"text": "KRC Genk | Zaterdag is er opnieuw een open stadiontour http://t.co/tSbZ2fYG",
"created_at": "Fri Nov 02 12:49:34 +0000 2012"

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/13196353/converting-date-to-correct-format

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