我有一个应用程序,使用每个日历组件的Calendar.component记录开始时间和日期(即let hour = calendar.component(.hour,from:date))并在之后将数据发送到Google表单按下另一个按钮。当分钟或秒以0开始时,0会被丢弃,我得到一个这样的结果:4:2:3应该是04:02:03。
以下是代码:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from:date)
let minutes = calendar.component(.minute, from:date)
let seconds = calendar.component(.second, from:date)
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
startTime = "\(hour):\(minutes):\(seconds)"
startDate = "\(month)/\(day)/\(year)"
答案 0 :(得分:0)
// unnecessary code
/* let calendar = Calendar.current
let hour = calendar.component(.hour, from:date)
let minutes = calendar.component(.minute, from:date)
let seconds = calendar.component(.second, from:date)
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
*/
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss"
var startTime = dateFormatter.string(from: date)
dateFormatter.dateFormat = "M/dd/yyyy"
var startDate = dateFormatter.string(from: date)