You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift(iOS)中Google Maps两段天/时/分格式行程时长相加实现求助

How to Add Two Trip Durations (Days/Hours/Minutes) in Swift for Google Maps

Hey there! Let's break down how to solve this duration addition problem. Since you've already fetched the two leg durations (start to waypoint, waypoint to end) from Google Maps' JSON response, the core idea is to convert both durations into a single common unit (like total minutes), sum them up, then convert back to the days-hours-minutes format. Here's a step-by-step solution:

1. Define a Struct to Hold Duration Components

First, create a simple struct to encapsulate the days, hours, and minutes of a single trip leg:

struct TripDuration {
    let days: Int
    let hours: Int
    let minutes: Int
}

2. Add Extensions for Conversion Logic

We'll add extensions to TripDuration to handle converting between structured duration and total minutes:

Convert Duration to Total Minutes

This turns your days/hours/minutes into a single integer of total minutes, making addition trivial:

extension TripDuration {
    func toTotalMinutes() -> Int {
        // 1 day = 24h = 1440 mins; 1 hour = 60 mins
        return days * 24 * 60 + hours * 60 + minutes
    }
}

Convert Total Minutes Back to Days/Hours/Minutes

After summing the total minutes, convert it back to the structured format:

extension TripDuration {
    static func fromTotalMinutes(_ totalMinutes: Int) -> TripDuration {
        let days = totalMinutes / (24 * 60)
        let remainingAfterDays = totalMinutes % (24 * 60)
        let hours = remainingAfterDays / 60
        let minutes = remainingAfterDays % 60
        
        return TripDuration(days: days, hours: hours, minutes: minutes)
    }
}

3. Put It All Together in Practice

Assuming you've already parsed your JSON responses into TripDuration instances, here's how to combine them:

// Example: Parsed durations from your Google Maps API calls
let startToWaypoint = TripDuration(days: 1, hours: 2, minutes: 30)
let waypointToEnd = TripDuration(days: 0, hours: 4, minutes: 45)

// Calculate total minutes
let combinedTotalMinutes = startToWaypoint.toTotalMinutes() + waypointToEnd.toTotalMinutes()

// Convert back to days/hours/minutes
let combinedDuration = TripDuration.fromTotalMinutes(combinedTotalMinutes)

// Result: days:1, hours:7, minutes:15
print("Combined Duration: \(combinedDuration.days)d \(combinedDuration.hours)h \(combinedDuration.minutes)m")

Bonus: Parsing Duration Strings from JSON

If your JSON returns duration as a human-readable string (e.g., "1 day 2 hours 30 mins"), here's a quick parsing function to convert it to TripDuration:

func parseDurationString(_ rawString: String) -> TripDuration {
    var days = 0, hours = 0, minutes = 0
    let parts = rawString.components(separatedBy: .whitespaces)
    
    for index in 0..<parts.count {
        guard let value = Int(parts[index]) else { continue }
        
        if index + 1 < parts.count {
            let unit = parts[index + 1].lowercased()
            switch unit {
            case let u where u.contains("day"):
                days = value
            case let u where u.contains("hour"):
                hours = value
            case let u where u.contains("min"):
                minutes = value
            default:
                break
            }
        }
    }
    
    return TripDuration(days: days, hours: hours, minutes: minutes)
}

// Usage example
let rawDuration = "1 day 2 hours 30 mins"
let parsedDuration = parseDurationString(rawDuration)

This approach keeps your code clean, reusable, and easy to maintain. Let me know if you need help adapting any part to your specific implementation!

内容的提问来源于stack exchange,提问作者kopalli ramya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:32:43