首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何获取整数格式的NSDate日、月、年?

如何获取整数格式的NSDate日、月、年?
EN

Stack Overflow用户
提问于 2011-06-02 19:44:33
回答 9查看 68.8K关注 0票数 96

我想以整数形式获得NSDate的日、月和年组件,即如果日期是1/2/1988,那么我应该将1、2和1988分别作为一个整数。我如何在iOS中做到这一点?我发现了类似的问题,但是descriptionWithCalendarFormat:方法给出了一个警告,现在似乎已经被弃用了。

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2015-08-23 22:54:30

斯威夫特

代码语言:javascript
复制
let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
let day = components.day
let month = components.month
let year = components.year

为方便起见,您可以将此代码放在NSDate扩展中,并使其返回一个元组:

代码语言:javascript
复制
extension NSDate: Comparable {

    var dayMonthYear: (Int, Int, Int) {
        let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
        return (components.day, components.month, components.year)
    }
}

现在你只需要写:

代码语言:javascript
复制
let (day, month, year) = date.dayMonthYear

如果你只想获取年份,你可以这样写:

代码语言:javascript
复制
let (_, _, year) = date.dayMonthYear
票数 13
EN

Stack Overflow用户

发布于 2011-06-02 19:46:39

给你,

代码语言:javascript
复制
NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate]; // Get necessary date components

 [components month]; //gives you month
 [components day]; //gives you day
 [components year]; // gives you year

你可以使用NSDateComponents来完成上面的操作。

有关详情,请访问this page

希望能有所帮助。

票数 223
EN

Stack Overflow用户

发布于 2011-06-02 19:50:48

是的,通过使用NSCalendar,我认为这将使您的工作。

代码语言:javascript
复制
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];    
NSInteger month = [components month];
NSInteger year = [components year];
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6214094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档