在swift 3.0中以分钟为单位转换时间

时间:2018-03-05 07:20:39

标签: swift xcode

data: [
{
schedule_id: "1",
schedule_name: "Garage Out",
schedule_lat: "22.5737085",
schedule_long: "88.4317922",
sehedule_time: "07:10 AM",
schedule_icon: "",
schedule_note: "EN-27, EN Block, Sector V, Salt Lake City, Kolkata, West Bengal 700091, India",
active_status: "0",
trip_id: "0"
}

上面我从JSON获得字符串格式的时间。 我将如何在几分钟内将其转换为快速

例如: -  07:10分钟= 430

2 个答案:

答案 0 :(得分:0)

你可以这样做

var str = "07:10 AM"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a" //Your date format
dateFormatter.timeZone = TimeZone.current //Current time zone
let date = dateFormatter.date(from: str) //according to date format your date string
print(date ?? "") //Convert String to Date

let calendar = Calendar.current
let comp = calendar.dateComponents([.hour, .minute], from: date!)
let hour = comp.hour ?? 0
let minute = comp.minute ?? 0
print(hour)
let finalMinut:Int = (hour * 60) + minute
print(finalMinut)

<强>输出

430

答案 1 :(得分:0)

这是解决方案:

    let time = "07:10 AM"
    let formatter = DateFormatter()
    formatter.dateFormat = "hh:mm a"

    let date = formatter.date(from: time)
    let calendar = Calendar(identifier: .gregorian)


    var currentDateComponent = calendar.dateComponents([.hour, .minute], from: date!)
    let numberOfMinutes = (currentDateComponent.hour! * 60) + currentDateComponent.minute!
    print("numberOfMinutes :: ", numberOfMinutes)