iOS将日期转换为字符串AM / PM

时间:2015-03-11 14:11:21

标签: ios objective-c nsdate

-(NSString *)calculateDateToString:(NSDate *)getDate
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    NSString *dateString = [dateFormat stringFromDate:getDate];
    return  dateString;
}

此方法在时间格式24H时工作,但如果AM / PM时间到来,则此方法不起作用。

我设置了日期格式,但仍然没有工作哪个部分错了任何想法请帮助?

编辑:

-(NSString *)calculateDateToString:(NSDate *)getDate
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

    NSString *dateString = [dateFormat stringFromDate:getDate];
    NSDate *aDate = [dateFormat dateFromString:dateString];

    if(!aDate)
    {
        [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss a"];
        aDate = [dateFormat dateFromString:dateString];
    }

    NSString *dateStringReturn = [dateFormat stringFromDate:aDate];
    return  dateStringReturn;
}

仍然返回null哪个部分错了?

编辑2:

-(NSDate *)calculateStringToDate:(NSString *)getString
{

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

    NSDate *aDate = [dateFormat dateFromString:getString];

    if(!aDate)
    {
        [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss a"];
        aDate = [dateFormat dateFromString:getString];
    }
    return aDate;
}

getString:2015-02-16T14:45:00

2 个答案:

答案 0 :(得分:3)

为我工作:

-(NSDate *)calculateStringToDate:(NSString *)getString
{

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

    NSDate *aDate = [dateFormat dateFromString:getString];

    if( !aDate )
    {
        [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss a"];
        [dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
        aDate = [dateFormat dateFromString:getString];
    }

    return aDate;
}

当我有一个像2015-02-16T14:45:00这样的字符串并且我想将其格式化为12H格式时,我只需要定义好本地。有关详细信息,请参阅here

希望这可以提供帮助;)

答案 1 :(得分:0)

如果您想使用上午/下午格式输出日期,请使用 a [dateFormat setDateFormat:@"YYYY-MM-dd'T'hh:mm:ss a"];

编辑:

相反,从NSString转换为NSDate,如果提供的字符串不符合格式,则可以使用返回dateFromString的{​​{1}}:

nil