ios - 有没有办法检测 NSDate 在哪个千年?

标签 ios objective-c nsdate

我有一个来自 01/01/14 字符串的 NSDate。不幸的是,字符串是用两位数保存的,所以我不知道年份是 1900 年代还是 2000 年代。但我想创建一些智能代码来猜测全年是什么千年和世纪。我知道一个事实(基于我正在创建的应用程序),在 99% 的情况下年份不能低于 1900。

我已将日期转换为现在显示四位数字,但它现在显示为 01/01/0014

有没有办法将 NSDate 的千禧年检测为 0 并相应地进行更改?

我真正想做的是这样的(伪代码):

if (millennium == 0 && decade < 15 && decade > 99)
{
   millennium = 2;
   century = 0;
   // change the date to 2000's here
}
else if (millennium == 00)
{
   millennium = 1;
   century = 9;
   // change the date to 1900's here
}

最佳答案

对于初学者,您的伪代码不太正确(第一个 if 语句是不可能的条件,因为 decade 不能同时小于 15 和大于 99)。

我已经使用 NSDateComponents 创建了一个基本解决方案,并为何时更改您可以轻松更改的年份制定了我自己的条件。

NSDate *date; // this is your date

NSDateComponents* components = [[NSCalendar currentCalendar] components: NSMonthCalendarUnit | NSDateCalendarUnit | NSYearCalendarUnit fromDate:date];

if([components year] < 15) // 2000 to 2015
{
  [components setYear:[components year] + 2000];
}
else if([components year] < 100) // 1915 to 1999
{
  [components setYear:[components year] + 1900];
}

date = [NSCalendar currentCalendar] dateFromComponents:components];

关于ios - 有没有办法检测 NSDate 在哪个千年?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23937188/

相关文章:

iOS Storyboard 约束未按预期运行

ios - 解读 iOS 崩溃报告

iphone - 当我的手指移动时如何填充图像的透明区域

ios - 找出superview的类名

swift - 将时间转换为 Double Swift

javascript - 如果在 resize 事件后调用 Google Maps API fitBounds() 行为会有所不同

objective-c - UICollectionViewData indexPathForItemAtGlobalIndex 断言失败

ios - 如何获取 "yyyy-MM-dd' T'HH :mm:ss. SSSZ"格式的日期?

ios - 预定的本地通知不规则

iphone - UIFileSharingEnabled 只保存文件