如何在swift3中获取实际时间和日期

时间:2017-10-12 07:05:29

标签: ios image swift3

我正在尝试将图片上传到服务器

我的网址是 - https://www.zdoof.com/api/zTimeline/insert_post

我的参数是 -

       "Is_checkin" : "0",
        "Description" : self.cookingText.text!,
        "Videolink" : "",
        "Post_image" : imageStr,
        "Created_by" : "4490",
        "Created_on" : "10/Oct/2017"

  The parameter(Created_on) taking the date & time  format like (dd/MMM/yyyy HH:mm:ss).

当我只提供日期格式(10/10月/ 2017)时,上传成功。但默认情况下需要时间,如12:00:00。

但我想把实际时间作为参数。如何编码日期和时间格式,以便它给出实际时间。

我的代码的日期和时间是 -

 let dateFormatter : DateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MMM/yyyy"

    let date = Date()
    let myString = dateFormatter.string(from: date)

    let data = myString.data(using: .utf8)



    self.dateString = String(data: data!, encoding: .utf8)!

  )


    let timeFormatter : DateFormatter = DateFormatter()
    timeFormatter.dateFormat = "HH:mm:ss"

    let calendar = NSCalendar.current
    let hour = calendar.component(.hour,from: NSDate() as Date)
    let minute = calendar.component(.minute,from: NSDate() as Date)
    let second = calendar.component(.second,from: NSDate() as Date)

    let hourString = String.init(describing: hour)
    let minuteString = String.init(describing: minute)
    let secondString = String.init(describing: second)
    self.timeString = hourString + ":" + minuteString + ":" + secondString

请帮助我将日期和时间转换为实际日期和时间

2 个答案:

答案 0 :(得分:1)

享受:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MMM/yyyy HH:mm:ss"

let formattedDate = dateFormatter.string(from: Date())

请记住,dateFormatter是“昂贵的”所以最好有一些带有静态或单例dateFormatter对象的辅助类

答案 1 :(得分:0)

也许你可以尝试一下:

 let formatter = DateFormatter()
 formatter.dateFormat = "dd/MMM/yyyy HH:mm:ss"
 let fullDateString = formatter.string(from: Date())

 formatter.dateFormat = "HH:mm:ss"
 let timeString = formatter.string(from: Date())