Yog*_*ogi 95 iphone datetime date nsdate nsdateformatter
我想得到NSDate整数形式的日,月和年组件,即如果日期是1/2/1988那么我应该分别得到1,2和1988作为整数.我怎么能在iOS中这样做?我发现了类似的问题,但方法是descriptionWithCalendarFormat:给出警告,现在似乎已被弃用了.
Jan*_*mal 222
这个给你,
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
Run Code Online (Sandbox Code Playgroud)
您可以像上面那样使用NSDateComponents.
请访问此页面了解详情.
希望能帮助到你.
use*_*278 17
是的,通过使用NSCalendar,我认为这将使你的工作.
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
Run Code Online (Sandbox Code Playgroud)
Ixx*_*Ixx 13
迅速
let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
let day = components.day
let month = components.month
let year = components.year
Run Code Online (Sandbox Code Playgroud)
为方便起见,您可以将其放在NSDate扩展名中并使其返回元组:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
现在你只需要写:
let (day, month, year) = date.dayMonthYear
Run Code Online (Sandbox Code Playgroud)
如果你想例如只获得你可以写的年份:
let (_, _, year) = date.dayMonthYear
Run Code Online (Sandbox Code Playgroud)
您可以使用NSDateComponents来实现此目的,
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currDate = [NSDate date];
NSDateComponents *dComp = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:currDate];
int day = [dComp day];
int month = [dComp month];
int year = [dComp year];
Run Code Online (Sandbox Code Playgroud)
小智 7
对于那些只是直接从网上复制和粘贴的人,就像我一样,这是iOS 8的一个小更新
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
[components day]; //Day
[components month];//Month
[components year];//Year
Run Code Online (Sandbox Code Playgroud)
差异NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit已被弃用
extension Date{
var day:Int {return Calendar.current.component(.day, from:self)}
var month:Int {return Calendar.current.component(.month, from:self)}
var year:Int {return Calendar.current.component(.year, from:self)}
}
Date().day//22
Date().month//4
Date().year//2017
Run Code Online (Sandbox Code Playgroud)
Swift 3.0(它是以前答案的迭代,但是为所有未来的应用程序项目解决了它)
| 归档时间: |
|
| 查看次数: |
66985 次 |
| 最近记录: |