修改其中一段
//
// From SwiftUI by Example by Paul Hudson
// https://www.hackingwithswift.com/quick-start/swiftui
//
// You're welcome to use this code for any purpose,
// commercial or otherwise, with or without attribution.
//
import SwiftUI
struct ContentView: View {
@State private var birthDate = Date()
let calendar = Calendar.current
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()
var body: some View {
VStack {
DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) {
Text("Select a date")
}
Text("Date is \(birthDate, formatter:dateFormatter) and sum is :\(calendar.dateComponents([.year], from: birthDate).year!+calendar.dateComponents([.month], from: birthDate).month!+calendar.dateComponents([.day], from: birthDate).day!)")
}
}
}
謝謝海綿寶寶大神的解答,順利可以作計算了!
問題解決就好
不好意思,再請教一個問題。
我想做陽曆轉農曆,找到了以下的程式碼可以實現,但得到的是日期是String格式。
我想提取這個農曆的年月日,做同樣的數學運算,請問該怎麼寫才可以呢?
非常感謝!
func solarToLunar(year: Int, month: Int, day: Int) -> String {
//初始化公曆
let solarCalendar = Calendar.init(identifier: .gregorian)
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = 12
components.minute = 0
components.second = 0
components.timeZone = TimeZone.init(secondsFromGMT: 60 * 60 * 8)
let solarDate = solarCalendar.date(from: components)
//初始化農曆
let lunarCalendar = Calendar.init(identifier: .chinese)
//日期格式和輸出
let formatter = DateFormatter()
//formatter.locale = Locale(identifier: "zh_TW")
formatter.dateStyle = .medium
formatter.calendar = lunarCalendar
return formatter.string(from: solarDate!)
}