DateExtensions.swift 1.1 KB

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