2021-12-28 20:39:12 +01:00
|
|
|
//
|
|
|
|
// DateOnly.swift
|
|
|
|
// xdrip
|
|
|
|
//
|
|
|
|
// Created by Eduardo Pietre on 28/12/21.
|
|
|
|
// Copyright © 2021 Johan Degraeve. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
|
2021-12-31 13:26:44 +01:00
|
|
|
/// Swift has no class to represent a day
|
2022-01-10 23:04:12 +01:00
|
|
|
/// - NSDate will always have time information together
|
|
|
|
/// - DateOnly will act as a wrapper for this purpose.
|
2021-12-28 20:39:12 +01:00
|
|
|
public struct DateOnly: Comparable, Equatable, Hashable {
|
|
|
|
|
|
|
|
// MARK: - Properties.
|
|
|
|
|
2021-12-31 13:26:44 +01:00
|
|
|
/// A Date object, used for comparations.
|
|
|
|
/// Should always have time zeroed.
|
2021-12-28 20:39:12 +01:00
|
|
|
public let date: Date
|
|
|
|
|
|
|
|
// MARK: - Public
|
|
|
|
|
2021-12-31 13:26:44 +01:00
|
|
|
/// Creates a DateOnly from a Date object.
|
2021-12-28 20:39:12 +01:00
|
|
|
init(date: Date) {
|
2022-01-10 23:04:12 +01:00
|
|
|
|
2021-12-28 20:39:12 +01:00
|
|
|
let calendar = Calendar.current
|
|
|
|
// Extracts the day, month and year for date
|
|
|
|
let dateComponents = calendar.dateComponents([.day, .month, .year], from: date)
|
|
|
|
|
|
|
|
// Because the values are from an existing date object,
|
|
|
|
// we can be sure they are not invalid args
|
|
|
|
// and use Force-unwrap ('!') .
|
|
|
|
self.date = calendar.date(from: dateComponents)!
|
2022-01-10 23:04:12 +01:00
|
|
|
|
2021-12-28 20:39:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// MARK: - Protocols
|
|
|
|
|
2021-12-31 13:26:44 +01:00
|
|
|
/// Hashable Protocol
|
2021-12-28 20:39:12 +01:00
|
|
|
public func hash(into hasher: inout Hasher) {
|
|
|
|
// Only the date is enough to identify each DateOnly.
|
|
|
|
hasher.combine(self.date)
|
|
|
|
}
|
|
|
|
|
2021-12-31 13:26:44 +01:00
|
|
|
/// Comparable Protocol
|
2021-12-28 20:39:12 +01:00
|
|
|
public static func < (lhs: DateOnly, rhs: DateOnly) -> Bool {
|
|
|
|
// Just use the date object.
|
|
|
|
return lhs.date < rhs.date
|
|
|
|
}
|
|
|
|
|
2021-12-31 13:26:44 +01:00
|
|
|
/// Equatable Protocol
|
2021-12-28 20:39:12 +01:00
|
|
|
public static func == (lhs: Self, rhs: Self) -> Bool {
|
|
|
|
// Just use the date object.
|
|
|
|
return lhs.date == rhs.date
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|