OStack程序员社区-中国程序员成长平台

标题: iphone - 如何将日期的年份更改为当前年份? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 01:32
标题: iphone - 如何将日期的年份更改为当前年份?

我有一个类似下面的数组

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 的 future 。



Best Answer-推荐答案


这段代码会为你做的:

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/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4