Skip to content

Commit f17ae8b

Browse files
[FEAT] added date with time extension to date (#16)
1 parent 9e30bb1 commit f17ae8b

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
//
2+
// Date+dateWithTime.swift
3+
// YCalendarPicker
4+
//
5+
// Created by Sahil Saini on 27/07/23.
6+
// Copyright © 2023 Y Media Labs. All rights reserved.
7+
//
8+
9+
import Foundation
10+
/// Add `dateWithTime` computed property
11+
extension Date {
12+
/// Returns a new `Date` representing the date calculated by setting hour, minute, and second
13+
/// to current values on a specified `Date` using the local time zone.
14+
public var dateWithTime: Date? {
15+
let currentDate = Date()
16+
let hours = Calendar.current.component(.hour, from: currentDate)
17+
let minutes = Calendar.current.component(.minute, from: currentDate)
18+
let seconds = Calendar.current.component(.second, from: currentDate)
19+
20+
return Calendar.current.date(bySettingHour: hours, minute: minutes, second: seconds, of: self)
21+
}
22+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//
2+
// Date+dateWithTime.swift
3+
// YCalendarPicker
4+
//
5+
// Created by Sahil Saini on 27/07/23.
6+
// Copyright © 2023 Y Media Labs. All rights reserved.
7+
//
8+
9+
import XCTest
10+
import YCalendarPicker
11+
12+
final class DateWithTime: XCTestCase {
13+
func testDateWithTimeHasCorrectDate() throws {
14+
let date = try XCTUnwrap(makeDate())
15+
guard let sut = date.dateWithTime else {
16+
XCTFail("Unable to get date with time")
17+
return
18+
}
19+
20+
let comp1 = Calendar.current.dateComponents([.year, .month, .day], from: date)
21+
let comp2 = Calendar.current.dateComponents([.year, .month, .day], from: sut)
22+
23+
XCTAssertEqual(comp1.year, comp2.year)
24+
XCTAssertEqual(comp1.month, comp2.month)
25+
XCTAssertEqual(comp1.day, comp2.day)
26+
}
27+
28+
func testDateOnlyHasNoTime() throws {
29+
let date = try XCTUnwrap(makeDate())
30+
guard let sut = date.dateWithTime else {
31+
XCTFail("Unable to get date with time")
32+
return
33+
}
34+
let timeDate = Date()
35+
36+
let components = Calendar.current.dateComponents([.hour, .minute, .second, .nanosecond], from: sut)
37+
let expectedComponents = Calendar.current.dateComponents([.hour, .minute, .second, .nanosecond], from: timeDate)
38+
39+
XCTAssertEqual(components.hour, expectedComponents.hour)
40+
XCTAssertEqual(components.minute, expectedComponents.minute)
41+
XCTAssertEqual(components.second, expectedComponents.second)
42+
XCTAssertEqual(components.nanosecond, 0)
43+
}
44+
}
45+
46+
private extension DateWithTime {
47+
func makeDate() -> Date? {
48+
Date()
49+
.date(byAddingMonth: Int.random(in: -6...6))?
50+
.date(byAddingDays: Int.random(in: -15...15))
51+
}
52+
}

0 commit comments

Comments
 (0)