Skip to content

Instantly share code, notes, and snippets.

@kot331107
Last active June 6, 2022 11:10
Show Gist options
  • Save kot331107/bb7bc18daebc488151b15a09917e0419 to your computer and use it in GitHub Desktop.
Save kot331107/bb7bc18daebc488151b15a09917e0419 to your computer and use it in GitHub Desktop.
Swift: get total days of DateComponents with a fractional part (including hours, minutes, etc)
//
// main.swift
// swift challenges
//
// Created by Filipp Mikheev on 06.06.22.
//
import Foundation
extension DateComponents {
var totalDays: Float {
get {
return (Float)(day ?? 0)
+ ((Float)(hour ?? 0)
+ ((Float)(minute ?? 0)
+ ((Float)(second ?? 0)
+ (Float)(nanosecond ?? 0)/1000)/60)/60)/24
}
}
}
// USAGE
let dateComponents = Calendar.current.dateComponents(
[.day, .hour, .minute, .second, .nanosecond],
from:start,
to: end)
print(dateComponents.totalDays)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment