簡體   English   中英

Swift-從月,日,年組件中獲取日期

[英]Swift - Getting Date from Month, Day, Year Components

如何將DateComponents轉換為Date對象。 目前,我有以下代碼

Calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))

但出現錯誤,指出"No 'date' candidates produce the expected contextual result type 'Date'

抱歉,這個基本問題很嚴重,但是我仍然在如何在Swift中處理日期方面苦苦掙扎

您不能調用date(from類型上的。您必須使用日歷的實例 ,即current日歷

Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 15))

或固定的

let calendar = Calendar(identifier: .gregorian)
calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
//create an instance of DateComponents to keep your code flexible
var dateComponents = DateComponents()

//create the date components
dateComponents.year = 2018
dateComponents.month = 1
dateComponents.day = 15
//dateComponents.timeZone = TimeZone(abbreviation: "EST")
dateComponents.hour = 4
dateComponents.minute = 12

//make something useful out of it
func makeACalendarObject(){

//create an instance of a Calendar for point of reference ex: myCalendar, and use the dateComponents as the parameter
let targetCalendar = Calendar.current
let newCalendarObject = targetCalendar.date(from: dateComponents)


guard let newCalObject = newCalendarObject else {
    return
}
print(newCalObject)
}
//call the object
makeACalendarObject()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM