Home > Back-end >  How to find sum of 2 date/time string in swift 5
How to find sum of 2 date/time string in swift 5

Time:02-13

I have multiple date/time string inside a loop

for item in self.sleepingActivityData ?? [] {
                    let value = Util.getFormattedDateString(inputDateString: self.findDateDiff(time1Str: item.startsAt ?? "", time2Str: item.endsAt ?? ""), inputDateFormat: "h m", outputDateFormat: "HH:mm")
                    print(value as Any) // "00:45"
                    
                }

value of 'value' is "00:45", "00:30", "00:45". I want to add this 3 timeString, So the sum should be "02:00" how can I achieve this in swift?

This is my getFormattedDateString() func:

static func getFormattedDateString(inputDateString: String, inputDateFormat: String, outputDateFormat: String) -> String?{
        let dateFormatterInput = DateFormatter()
        dateFormatterInput.dateFormat = inputDateFormat//"yyyy-MM-dd HH:mm:ss"
        
        let dateFormatterOutput = DateFormatter()
        dateFormatterOutput.dateFormat = outputDateFormat//"EEEE, MMM dd hh:mm a"
        
        if let date = dateFormatterInput.date(from: inputDateString) {
            return (dateFormatterOutput.string(from: date))
        } else {
            return nil
        }
    }

& thats how I found the difference between 2 time in findDateFiid() func:

   func findDateDiff(time1Str: String, time2Str: String) -> String {
        let timeformatter = DateFormatter()
        timeformatter.dateFormat = "HH:mm:ss"

        guard let time1 = timeformatter.date(from: time1Str),
            let time2 = timeformatter.date(from: time2Str) else { return "" }
        //You can directly use from here if you have two dates
        let interval = time2.timeIntervalSince(time1)
        let hour = interval / 3600;
        let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
        return "\(Int(hour)) \(Int(minute))"
    }

CodePudding user response:

I coded this in playground, you cam replace date dateArray with your own array: self.sleepingActivityData

import UIKit

var dateArray = ["00:45", "00:30", "00:45"]
var sumH: Int = Int()
var sumM: Int = Int()

for (index, item) in dateArray.enumerated() {
    print(item as Any) // "00:45"
    if index < dateArray.count {
        addTime(timeStr: dateArray[index])
    }
}

func addTime(timeStr: String) {
    let values = timeStr.components(separatedBy: ":")
    //sum hours
    guard let h = Int(values[0]) else {return}
    //sum minutes
    guard let m = Int(values[1]) else {return}

    sumM = sumM   m
    sumH = sumH   h
    
    if sumM >= 60 {
        sumM = sumM - 60
        sumH = sumH 1
    }
    
    print("hours:",sumH)
    print("minutes:",sumM)
}

CodePudding user response:

There is no string-date-math API.

Basically you need two methods to convert HH:mm to minutes and vice versa

func hhmmToMinutes(_ hhmm : String) -> Int {
    let components = hhmm.components(separatedBy: ":")
    guard components.count == 2,
          let hr = Int(components[0]),
          let mn = Int(components[1]) else { return 0 }
    return hr * 60   mn
}

func minutesToHourMinute(_ minutes : Int) -> String {
    let hr = minutes / 60
    let mn = minutes % 60
    return String(format: "ld:ld", hr, mn)
}

Then you use can higher level API to do the time math

let array = ["00:45", "00:30", "00:45"]
let minutes = array.map{hhmmToMinutes($0)}.reduce(0,  )
let timeString = minutesToHourMinute(minutes)
print(timeString) // 02:00
  • Related