【问题标题】:Struggling to store a date for later use努力存储一个日期以备后用
【发布时间】:2011-12-29 03:47:45
【问题描述】:

您好,我是 iOS 编程的新手,正在玩弄日期(今天的日期和一年后的日期)。

这是我正在尝试的代码。

NSCalendar * calendar = [NSCalendar currentCalendar];//Create a calendar
NSDate *todaysDate = [[NSDate alloc]init]; //get todays date
NSString *dateToday = [NSString stringWithFormat:@"%@",todaysDate];//convert it to a string
NSDateFormatter *df = [[NSDateFormatter alloc] init];// create a formatter
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ" ];//input how the date looks as a string
myDate = [df dateFromString: dateToday];// change it back to a proper NSDate

NSDateComponents *components = [[NSDateComponents alloc] init]; // create the components
[components setYear:1];//add 1 year
nextYear = [calendar dateByAddingComponents:components toDate:todaysDate options:0]; // build the year from component into a variable


dateNextYear = [NSString stringWithFormat:@"%@",nextYear];//convert it to a string
NSDateFormatter *yearFormat = [[NSDateFormatter alloc] init];// create a formatter
[yearFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ" ];//input how the date looks as a string
myDateInTheFuture = [yearFormat dateFromString: dateNextYear];// change it back to a proper NSDate


NSLog(@" next years date is %@ ", myDateInTheFuture);
[yearFormat release];
[components release];
[todaysDate release];

我可以得到当前日期和 1 年后的未来日期,但我不确定如何存储未来日期以进行比较,我知道我可以使用 NSDate 的“比较”项目来检查,但是当我每次运行时都将未来日期设置为一个变量,它与我正在检查的是今天的日期相比保持相对 1 年。 现在是凌晨 3 点,我的大脑一片混乱,所以如果这是有史以来最简单的事情,而我只是看不到它,请提前道歉。

这是我的第一篇文章,所以请放轻松。 谢谢

【问题讨论】:

    标签: objective-c ios nsdate nsdateformatter nsdatecomponents


    【解决方案1】:

    我不完全确定您要做什么,但这是我收集到的:

    您想要获取当前日期,为其添加年份,然后操作生成的日期。

    如果这不正确,请通知我。

    为此,请尝试以下操作:

    NSDate *todayDate = [NSDate date]; //Create a date that is set to today
    NSDate *resultingDate = [calendar dateByAddingTimeInterval:31556926; //Take the current date and add the amount of seconds in a year to it
    

    如果你想永久保存,使用 NSUserDefaults:

    设置:

    [userDefaults setObject:resultingDate forKey:@"storedDate"];
    

    希望这会有所帮助,

    哈尔加瓦

    得到:

    NSDate *returnedDate = [userDefaults dateForKey:@"storedDate"];
    

    【讨论】:

    • 使用硬编码的时间间隔将日期调整 N 天/周/年/等是一个可怕的想法 (tm),因为必须考虑大量特殊情况。恰当的例子:萨摩亚今年将取消 12 月 30 日。 bbc.co.uk/news/business-13330592 始终使用日期 API 来执行日历计算,并为自己省去很多麻烦。
    • 感谢 hbhargava 我一直在寻找的答案是用户默认路由,感谢您抽出宝贵时间帮助我,因为我似乎已经把我想要的东西复杂化了。欢呼
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2012-07-07
    • 1970-01-01
    相关资源
    最近更新 更多