【问题标题】:0 gets dropped when posting to Google Forms in Swift0 在 Swift 中发布到 Google 表单时被丢弃
【发布时间】:2017-08-26 04:48:31
【问题描述】:

我有一个应用程序,它使用 Calendar.component 为每个单独的日历组件(即 let hour = calendar.component(.hour, from:date))记录开始时间和日期,并在之后将数据发送到 Google 表单另一个按钮被按下。当 Minutes 或 seconds 以 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,因为它没用。按照下面我的答案获得正确的结果。

标签: ios swift


【解决方案1】:
  1. 您不需要单独的日历和日期对象。日期对象将两者兼而有之。
  2. DateFormatter 是这样做的正确方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2011-12-19
    • 1970-01-01
    相关资源
    最近更新 更多