没有年份的日期字符串与年份的NSDate

时间:2015-09-02 11:53:57

标签: ios objective-c nsdate nsdateformatter

我有一个日期字符串      “9月2日星期三下午5点09分”,来自服务器。     将字符串转换为NSDate时。     “2000-09-02 17:09:00 +0000”但这一年应该是“2015”像:     “2015-09-02 17:09:00 +0000”

这是我的代码,请告诉我问题在哪里

NSString *dateStr = @"5:09 pm Wed Sep 2";

// Convert string to date object
NSString *dateFormat=  ([self hasAMPM])?@"hh:mm a EEEE MMM d":@"hh:mm a EEEE MMM d" ;
    NSDate * date = [self toLocalTime:[self convertDateFromString:dateStr OutputFormat:dateFormat]];


///****
-(BOOL)hasAMPM{
    NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];

    NSRange containsA = [formatStringForHours rangeOfString:@"a"];
    BOOL hasAMPM = containsA.location != NSNotFound;
    return hasAMPM;
}

-(NSDate *)toLocalTime:(NSDate *)date
{
    NSTimeZone *tz = [NSTimeZone systemTimeZone];
    NSInteger seconds = [tz secondsFromGMTForDate: date];
    return [NSDate dateWithTimeInterval: seconds sinceDate: date];
}

-(NSDate *)convertDateFromString:(NSString *)strDate OutputFormat:(NSString *)outPutFormat
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:outPutFormat];

    NSDate *date1= [formatter dateFromString:strDate];
    return date1;
}

请帮助我摆脱这种情况。

2 个答案:

答案 0 :(得分:1)

如果您想根据当前日期在日期中添加年份,则此功能适用于1970年以后的日期,尚未检查以外的日期:

NSString *dateStr = @"5:09 pm Wed Sep 2";

NSString *dateString = [dateStr stringByAppendingString:@" 1970"];
// Convert string to date object
NSString *dateFormat=  ([self hasAMPM])?@"hh:mm a EE MMM d yyyy":@"hh:mm a EE MMM d yyyy" ;
NSDate * date = [self toLocalTime:[self convertDateFromString:dateString OutputFormat:dateFormat]];

NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
greCalendar.timeZone = [NSTimeZone systemTimeZone];

NSDateComponents *componenetsForCurrent = [greCalendar componentsInTimeZone:[NSTimeZone systemTimeZone] fromDate:[NSDate date]];
NSInteger year = componenetsForCurrent.year;



NSDate *requiredDate = [greCalendar dateByAddingUnit:NSCalendarUnitYear value:(year-1970) toDate:date options:NSCalendarWrapComponents];

答案 1 :(得分:0)

您可以使用NSDateComponents拆分日期,并独立使用年份

NSDateComponents *dateComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
[dateComponents setYear:someYear];
date = [calendar dateFromComponents:dateComponents];