2016-09-12 9 views
5

が、私はこのコードiosで今日の日付の開始時刻と終了時刻を取得する方法は?

let today: NSDate = NSDate() 
    let dateFormatter: NSDateFormatter = NSDateFormatter() 
    dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle 
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" 
    dateFormatter.timeZone = NSTimeZone(abbreviation: "SGT"); 
    print(dateFormatter.stringFromDate(today)) 

を使用して、現在の日付と時刻を取得していますが、私は今日の日付の時間と終了時間を開始取得したい

例: 12-09-2016 00:00:00 AND 12-09-2016 23:59:59

どのように起動しますし、現在の日付の終了時刻?

+4

'NSDate()' '今' 与えます。あなたは 'NSDateComponents'を利用し、' hour''''''''sec''と '' nanosecond''コンポーネントを設定することができます。 [this](http://stackoverflow.com/q/13324633/2710486) – zcui93

答えて

10

startOfDayForDateを使用すると、今日の真夜中の日付を取得し、その日から終了時刻を取得できます。

//For Start Date 
let calendar = NSCalendar.currentCalendar() 
calendar.timeZone = NSTimeZone(abbreviation: "UTC")! //OR NSTimeZone.localTimeZone() 
let dateAtMidnight = calendar.startOfDayForDate(NSDate()) 

//For End Date 
let components = NSDateComponents() 
components.day = 1 
components.second = -1 
let dateAtEnd = calendar.dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions()) 
print(dateAtMidnight) 
print(dateAtEnd) 

編集:文字列に変換

let dateFormatter = NSDateFormatter() 
dateFormatter.timeZone = NSTimeZone (abbreviation: "UTC")! // OR NSTimeZone.localTimeZone() 
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" 
let startDateStr = dateFormatter.stringFromDate(dateAtMidnight) 
let endDateStr = dateFormatter.stringFromDate(dateAtEnd) 
print(startDateStr) 
print(endDateStr) 
+0

Working.butテキストフィールドでこの値を取る方法 –

+0

ウェルカインメイト、ハッピーコーディング:) –

+1

「これをどうやってテキストフィールドの値 "?この日付をtextFieldに表示しますか? –

関連する問題