ios 将 NSString 转换为 NSDate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14640929/
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-08-30 22:06:13  来源:igfitidea点击:

Convert NSString to NSDate

iosobjective-cnsstringnsdate

提问by vivianaranha

Possible Duplicate:
Converting NSString to NSDate (and back again)

可能的重复:
将 NSString 转换为 NSDate(并再次返回)

I make a request to the flickr api and it returns me the date in the following format

我向 flickr api 发出请求,它以以下格式返回日期

"2013-02-01T06:25:47Z"

How do i convert this into NSDate format??

我如何将其转换为 NSDate 格式?

回答by Madhu

It's a simple one, converting NSString to NSDate we use NSDateformatter using dateFromString method. We need to provide the Dateformatter style with existing style for NSString

这是一个简单的,将 NSString 转换为 NSDate 我们使用 NSDateformatter 使用 dateFromString 方法。我们需要为 NSString 提供具有现有样式的 Dateformatter 样式

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:@"2013-02-01T06:25:47Z"];
NSTimeZone *pdt = [NSTimeZone timeZoneWithAbbreviation:@"PDT"];
[dateFormatter setTimeZone:pdt];
[dateFormatter setDateFormat:@"HH:mm:ss zzz"];
[dateFormatter setDateFormat:@"K:mm a, z"];
NSString * updated String = [dateFormatter stringFromDate:date];

回答by Nishant B

You can use below function:

您可以使用以下功能:

-(NSDate *)getDateFromString:(NSString *)pstrDate
{
    NSDateFormatter *df1 = [[[NSDateFormatter alloc] init] autorelease];
    [df1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate *dtPostDate = [df1 dateFromString:pstrDate];
    return dtPostDate;
}

Hope, it will be helpful to you.

希望,它会对你有所帮助。

This function will accept your string date and return the NSDate value.

此函数将接受您的字符串日期并返回 NSDate 值。

Cheers!

干杯!