xcode 在目标 c/iOS 中将日期字符串转换为 NSDate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14398604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:33:05  来源:igfitidea点击:

convert date string to NSDate in objective c/iOS

iphoneiosobjective-cxcode

提问by Paul.s

I have this string ----> Sun, 16 Dec 2012 15:30:22 +0000

我有这个字符串 ----> Sun, 16 Dec 2012 15:30:22 +0000

I want to convert it to NSDate. I have tried the below code but it is giving me null

我想将其转换为 NSDate。我已经尝试了下面的代码,但它给了我空

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

[df setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];

NSDate *date = [[NSDate alloc] init];

date = [df dateFromString: @"Sun, 16 Dec 2012 15:30:22 +0000"];

NSLog(@"date: %@", date);

I am not getting the issue ?

我没有得到这个问题?

Any guidance plz

任何指导请

回答by Paul.s

The dateFormatof the formatter needs to match the format of the string you are providing it with.

dateFormat的格式需要以符合您所向它提供字符串的格式。

Therefore something like this should work

因此这样的事情应该工作

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss ZZZ";

NSLog(@"%@", [formatter dateFromString:@"Fri, 18 Jan 2013 15:30:22 +0000"]);

To look up what the specifiers actually mean check Unicode Technical Standard #35

要查找说明符的实际含义,请查看Unicode Technical Standard #35

回答by P.J

Try this code

试试这个代码

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

    [df setDateFormat:@"EEEE, dd MMM yyyy"];

    NSDate *date = [[NSDate alloc] init];

    date = [df dateFromString: @"Sun, 16 Dec 2012"];

    NSLog(@"date: %@", date);

Hope it helps you..

希望能帮到你。。

EDIT :-

编辑 :-

For your string

对于你的字符串

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

    [df setDateFormat:@"EEEE, dd MMM yyyy HH:mm:ss z"];

    NSDate *date = [[NSDate alloc] init];

    date = [df dateFromString: @"Sun, 16 Dec 2012 15:30:22 +0000"];

    NSLog(@"date: %@", date);

回答by Satish Azad

Try this to get NSDate from String

试试这个从字符串中获取 NSDate

- (NSDate*) dateFromString:(NSString*)aStr
{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
    //[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss a"];
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSLog(@"%@", aStr);
    NSDate   *aDate = [dateFormatter dateFromString:aStr];
    [dateFormatter release];
    return aDate;
}

It works fine for me.

这对我来说可以。