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

iOS convert date to string AM/PM

-(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;
}

还是returnnull哪部分错了??

编辑 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

如果你想输出 am/pm 格式的日期,使用 a , [dateFormat setDateFormat:@"YYYY-MM-dd'T'hh:mm:ss a"];

编辑:

相反,从NSString转换成NSDate,如果提供的字符串不符合格式,你可以使用dateFromString 那returns nil:

NSString StringDate=@"10:10:10 AM"; 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"HH:mm:ss"];
NSDate *aDate = [dateFormat dateFromString:StringDate];
if(!aDate){
  [dateFormat setDateFormat:@"hh:mm:ss a"];
  aDate = [dateFormat dateFromString:StringDate];
}

为我工作:

-(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

希望对您有所帮助 ;)