DateExtensions.swift 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. // LoopFollow
  2. // DateExtensions.swift
  3. import Foundation
  4. // MARK: - Date Extension for NS Compatibility
  5. extension Date {
  6. /// Creates a new date with the original date's components but current seconds and milliseconds
  7. /// This prevents Nightscout issues with entries at the same exact time
  8. /// - Returns: A new date with randomized milliseconds
  9. func dateUsingCurrentSeconds() -> Date {
  10. let calendar = Calendar.current
  11. // Extracting components from the original date
  12. var components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: self)
  13. // Getting the current seconds and milliseconds
  14. let now = Date()
  15. let nowSeconds = calendar.component(.second, from: now)
  16. let nowMillisecond = calendar.component(.nanosecond, from: now) / 1_000_000
  17. // Setting the seconds and millisecond components
  18. components.second = nowSeconds
  19. components.nanosecond = nowMillisecond * 1_000_000
  20. // Creating a new date with these components
  21. return calendar.date(from: components) ?? self
  22. }
  23. }