gpt4 book ai didi

ios - 一个没有年份的日期字符串到有年份的 NSDate

转载 作者:行者123 更新时间:2023-11-29 01:41:19 25 4
gpt4 key购买 nike

我有一个日期字符串 “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;
}

请帮我摆脱这种情况。

最佳答案

如果你想根据当前日期在你的日期中添加年份,这适用于从 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];

关于ios - 一个没有年份的日期字符串到有年份的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32352451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com