This repository has been archived by the owner on Apr 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Date.swift
81 lines (70 loc) 路 2.21 KB
/
Date.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import Foundation
public extension Date {
static let hourInSec = 3600
static let minInSec = 60
static func startOfMonth() -> Date? {
return Date().startOfMonth()
}
static func endOfMonth() -> Date? {
return Date().endOfMonth()
}
func startOfMonth(calendar: Calendar = .current) -> Date? {
return calendar.date(
from: calendar.dateComponents([.year, .month],
from: calendar.startOfDay(for: self))
)
}
func endOfMonth(calendar: Calendar = .current) -> Date? {
guard let startOfMonth = self.startOfMonth() else { return nil }
return calendar.date(
byAdding: DateComponents(month: 1, day: -1),
to: startOfMonth
)
}
func add(days: Int, calendar: Calendar = .current) -> Date? {
return calendar.date(
byAdding: DateComponents(day: days),
to: self
)
}
func sub(days: Int, calendar: Calendar = .current) -> Date? {
return calendar.date(
byAdding: DateComponents(day: -days),
to: self
)
}
func add(hours: Int, calendar: Calendar = .current) -> Date? {
return calendar.date(
byAdding: DateComponents(hour: hours),
to: self
)
}
func sub(hours: Int, calendar: Calendar = .current) -> Date? {
return calendar.date(
byAdding: DateComponents(hour: -hours),
to: self
)
}
/// Set hour/min/sec of a date
///
/// Replaces `Calendar().date(bySettingHour hour: Int, minute: Int, ...)` which is not
/// running on Linux yet.
///
/// - Parameters:
/// - hour: Int
/// - minute: Int
/// - second: Int
/// - Returns: Date?
func dateBySetting(
hour: Int,
minute: Int,
second: Int,
calendar: Calendar = Calendar(identifier: .gregorian)
) -> Date? {
let dateComponents = calendar.dateComponents([.year, .month, .day], from: self)
guard let date = calendar.date(from: dateComponents) else { return nil }
return date.addingTimeInterval(
TimeInterval(hour * Date.hourInSec + minute * Date.minInSec + second)
)
}
}