web-dev-qa-db-ja.com

NSDateのNSDateComponents

単一のNSDateのNSDateComponentsを取得するにはどうすればよいですか? NSDateの秒、分、時間、日、月、年の2つの日付の差のコンポーネントが必要ないのですか?

26
cfischer

Apple docs 、リスト3に例があります:日付のコンポーネントを取得する

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
                    [gregorian components:(NSDayCalendarUnit | 
                                           NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];

componentsメソッドの呼び出しで必要な calendar units を一緒に「or」する必要があることに注意してください。

42
martin clayton

nSCalendarのメソッドを使用:

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date

お気に入り:

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDate *date = [NSDate date];


NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:unitFlags fromDate:date];
8
Grady Player

Apple Developer documentation、 DateComponents にはsecondminutehourdaymonthyearインスタンスプロパティ。次のSwift 5 Playgroundコードは、秒、分、時間、日、 Dateを使用したDateComponentsインスタンスからの月と年のコンポーネント:

import Foundation

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: "CET")!
let date = Date()

// Get seconds, minutes, hours, day, month and year
let components = calendar.dateComponents([.second, .minute, .hour, .day, .month, .year], from: date)
let seconds = components.second
let minutes = components.minute
let hours = components.hour
let day = components.day
let month = components.month
let year = components.year

// Print components
print(String(describing: seconds)) // prints Optional(33)
print(String(describing: minutes)) // prints Optional(42)
print(String(describing: hours)) // prints Optional(22)
print(String(describing: day)) // prints Optional(17)
print(String(describing: month)) // prints Optional(12)
print(String(describing: year)) // prints Optional(2016)

/* ... */

// Set a formatter in order to display date
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .long
formatter.timeZone = TimeZone(abbreviation: "CET")
formatter.locale = Locale(identifier: "fr_FR")
print(formatter.string(from: date)) // prints 17/12/2016 22:42:33 UTC+1
3
Imanou Petit

Swift 2.xでは、必要なコンポーネントがこのように渡されます。

let gregorianCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) 
let weekdayHourMinutes = gregorianCalendar?.components([.Weekday, .Hour, .Minute], fromDate: date)
0
orkoden