Date.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Date.swift
  2. // This file is part of KeePass.swift
  3. //
  4. // Copyright © 2021 Maxime Epain. All rights reserved.
  5. //
  6. // KeePass.swift is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // KeePass.swift is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with KeePass.swift. If not, see <https://www.gnu.org/licenses/>.
  18. import Binary
  19. import Foundation
  20. extension Database {
  21. public static let distantFuture: Date = {
  22. DateComponents(calendar: Calendar(identifier: .iso8601),
  23. year: 2999,
  24. month: 12,
  25. day: 28,
  26. hour: 23,
  27. minute: 59,
  28. second: 59,
  29. nanosecond: 0).date!
  30. }()
  31. public static func date(from bytes: Bytes) -> Date? {
  32. guard bytes.count > 4 else { return nil }
  33. let year = (Int(bytes[0]) << 6) | (Int(bytes[1]) >> 2)
  34. let month = ((Int(bytes[1]) & 0x0000_0003) << 2) | (Int(bytes[2]) >> 6)
  35. let day = (Int(bytes[2]) >> 1) & 0x0000_001F
  36. let hour = ((Int(bytes[2]) & 0x0000_0001) << 4) | (Int(bytes[3]) >> 4)
  37. let minute = ((Int(bytes[3]) & 0x0000_000F) << 2) | (Int(bytes[4]) >> 6)
  38. let second = Int(bytes[4]) & 0x0000_003F
  39. return DateComponents(calendar: Calendar(identifier: .iso8601),
  40. year: year,
  41. month: month,
  42. day: day,
  43. hour: hour,
  44. minute: minute,
  45. second: second,
  46. nanosecond: 0).date
  47. }
  48. public static func bytes(from date: Date) -> Bytes {
  49. let calendar = Calendar(identifier: .iso8601)
  50. let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
  51. let year = components.year!
  52. let month = UInt8(components.month!)
  53. let day = UInt8(components.day!)
  54. let hour = UInt8(components.hour!)
  55. let minute = UInt8(components.minute!)
  56. let second = UInt8(components.second!)
  57. var bytes = Bytes(lenght: 5)
  58. bytes[0] = UInt8(year >> 6) & 0x3F
  59. bytes[1] = (UInt8(year & 0x3F) << 2) | ((month >> 2) & 0x03)
  60. bytes[2] = ((month & 0x03) << 6) | ((day & 0x1F) << 1) | ((hour >> 4) & 0x01)
  61. bytes[3] = (hour & 0x0F) << 4 | ((minute >> 2) & 0x0F)
  62. bytes[4] = ((minute & 0x03) << 6) | (second & 0x3F)
  63. return bytes
  64. }
  65. }