gpt4 book ai didi

iphone - 如何将日期更改为当年?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:47:19 24 4
gpt4 key购买 nike

我有一个类似下面的数组

Birthdates(
"03/12/2013",
"03/12/2013",
"08/13/1990",
"12/09/1989",
"02/06",
"09/08",
"03/02/1990",
"08/22/1989",
"03/02",
"05/13",
"10/16",
"07/08",
"08/31/1990",
"04/14/1992",
"12/15/1905",
"08/14/1989",
"10/07/1987",
"07/25",
"07/17/1989",
"03/24/1987",
"07/28/1988",
"01/21/1990",
"10/13"
)

都是NSString

现在我想从中创建另一个数组,其中所有年份都应该是 2013 年,如果该日期在当年,如果日期已经过去,那么将年份更改为 2014 年?

在上面的句子中,我们不考虑年份,我们只考虑日期和月份,然后查看当前年份是否已经过去?

例如,如果日期是“12/15/1905”,则将其转换为另一个数组,例如“12/15/2013”但如果日期类似于“01/01/1990”,则将其转换为另一个数组,如“01/01/2014”因为它已经过了当前日期请帮助提前谢谢你:)

我更愿意做一些代码不仅适用于 2013 年和 2014 年而且也适用于 future 的事情。

最佳答案

此代码将为您完成:

NSArray *Birthdates=@[
@"03/12/2013",
@"03/12/2013",
@"08/13/1990",
@"12/09/1989",
@"02/02",
@"09/08",
@"03/02/1990",
@"08/22/1989",
@"03/02"];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger currentYear = [components year];

NSMutableArray *newBirthDates=[NSMutableArray new];

for(NSString *str in Birthdates){
NSArray *array=[str componentsSeparatedByString:@"/"];
if(array.count==2){
NSString *tempString=[NSString stringWithFormat:@"%@/%d",str,currentYear];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *date=[dateFormatter dateFromString:tempString];
if ([[NSDate date] isGreaterThanOrEqualTo:date]) {
NSLog(@"passed->%@ *** %@",date, str);
[newBirthDates addObject:[NSString stringWithFormat:@"%@/%d",str,currentYear+1]];
}
[newBirthDates addObject:tempString];
}
else{
NSString *dateString=[NSString stringWithFormat:@"%@/%@/%d",array[0],array[1],currentYear];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *date=[dateFormatter dateFromString:dateString];
if ([[NSDate date] isGreaterThanOrEqualTo:date]) {
dateString=[NSString stringWithFormat:@"%@/%@/%d",array[0],array[1],currentYear+1];
}

[newBirthDates addObject:dateString];
}
}
NSLog(@"%@",newBirthDates);

这是输出:

DocumentBased[6632:303] (
"03/12/2014",
"03/12/2014",
"08/13/2013",
"12/09/2013",
"02/02/2014",
"09/08/2013",
"03/02/2014",
"08/22/2013",
"03/02/2014"
)

关于iphone - 如何将日期更改为当年?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15378836/

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