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

问题描述 投票:0回答:2
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获得字符串格式的时间。我将如何在几分钟内将其转换为swift

例如: - 07:10分钟= 430

swift xcode
2个回答
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)

OUTPUT

430


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)
© www.soinside.com 2019 - 2024. All rights reserved.