在Swift中发布到Google表单时会丢弃0

时间:2017-08-25 20:33:14

标签: ios swift

我有一个应用程序,使用每个日历组件的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)"

1 个答案:

答案 0 :(得分:0)

  1. 你不需要日历&单独的日期对象。 Date Object将同时执行这两项操作。
  2. DateFormatter是执行此操作的正确方法。
  3.   

    //        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)