无法使用NSDateFormatter从字符串中解析日期 [英] Unable to parse date from string using NSDateFormatter

查看:42
本文介绍了无法使用NSDateFormatter从字符串中解析日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困了一段时间,使用 NSDateFormatter

I am stuck for a while parsing date in string using NSDateFormatter

字符串中的日期采用以下格式

Date in string is in below format

1/1/2011 12:00:00 AM

1/1/2011 12:00:00 AM

下面是我用来解析的代码

Below is the code I use to parse

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss"];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [[NSDate alloc]init];
date = [dateFormatter dateFromString:@"1/1/2011 12:00:00 AM"];

此代码适用于日期@"12/31/2011"和格式@"MM/dd/yyyy"

This code works with date @"12/31/2011" and format @"MM/dd/yyyy"

请帮助

推荐答案

使用我的波纹管自定义方法并将该日期解析为另一种格式...

use my bellow custom method and parse that date into another format...

-(NSString *)changeDateFormat:(NSString*)stringDate dateFormat:(NSString*)dateFormat getwithFormat:(NSString *)getwithFormat{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];

    NSDate *date = [dateFormatter dateFromString:stringDate];

    [dateFormatter setDateFormat:getwithFormat];

    NSString *convertedString = [dateFormatter stringFromDate:date];
    //NSLog(@"Converted String : %@",convertedString);
    return convertedString;
}

像下面这样使用这种方法.

use this method like bellow..

 NSString *strSDate = [self changeDateFormat:@"1/1/2011 12:00:00 AM" dateFormat:@"dd/MM/yyyy hh:mm:ss a" getwithFormat:@"dd/MM/yyyy"];
 NSLog(@"Converted String : %@",strSDate);

使用 getwithFormat 参数设置所需的任何格式,并使用带有日期字符串的 dateFormat 参数设置格式...

Set any Format which you want in getwithFormat parameter and set format in dateFormat parameter which you have with your Date string...

输出是=>转换后的字符串:2011年1月1日

这篇关于无法使用NSDateFormatter从字符串中解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆