gpt4 book ai didi

iphone - 获取下一个日期和前一天的日期

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:50:17 25 4
gpt4 key购买 nike

我基本上想将特定日期 (x) 转换为前一天的日期 (x - 1 天) 以及第二天的日期 (x + 1 天)。我为此使用以下代码:

NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];

但是我的日期 (x) 为 NSString 格式,在应用上述代码之前,我需要将 NSString(myDateString) 转换为 NSDate(myDate)。我有一个包含日期的 NSString,格式为 MM-dd-yyyy。为了进行转换,我使用了以下代码,但我得到了荒谬的值。

 NSLog(@"myDateString=%@",myDateString);//output:myDateString=10-25-2012//all correct
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-yyyy"];
NSDate *myDate=[formatter dateFromString:myDateString];
NSLog(@"myDate=%@",myDate);//output:myDate=2012-10-24 18:30:00 +0000 // I only want the date to be shown // and why has the format changed
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
NSLog(@"datePlusOneDay=%@",datePlusOneDay);//output:datePlusOneDay=2012-10-25 18:30:00 +0000// I only want the date to come , not time // and why has the format changed

稍后我需要再次将 NSDate 转换为 NSString

NSString *curentString=[formatter stringFromDate:datePlusOneDay];
NSLog(@"curentString=%@",curentString); //output:curentString=10-26-2012

同样我也想得到之前的日期。请大家帮忙!!和 ho ho 圣诞快乐!!

最佳答案

按照:componets.day = 1获取下一天,-1获取前一天。

NSDate *date = [NSDate date]; // your date from the server will go here.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];

NSLog(@"newDate -> %@",newDate);

关于iphone - 获取下一个日期和前一天的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028908/

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