Skip to content

Instantly share code, notes, and snippets.

@ShikiSuen
Created February 7, 2023 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShikiSuen/8b0e114560cf8e334ef45d8e6244a85c to your computer and use it in GitHub Desktop.
Save ShikiSuen/8b0e114560cf8e334ef45d8e6244a85c to your computer and use it in GitHub Desktop.
Swift Date Checker.
// (c) 2021 and onwards The vChewing Project (MIT License).
// ====================
// This code is released under the MIT license (SPDX-License-Identifier: MIT)
import Foundation
extension Date {
/// Check whether current date is the given date.
/// - Parameter dateDigits: `yyyyMMdd`, 8-digit integer. If only `MMdd`, then the year will be the current year.
/// - Returns: The result. Will return false if the given dateDigits is invalid.
public static func isTodayTheDate(from dateDigits: Int) -> Bool {
let currentYear = Self.currentYear
var dateDigits = dateDigits
let strDateDigits = dateDigits.description
switch strDateDigits.count {
case 3, 4: dateDigits = currentYear * 10000 + dateDigits
case 8:
if let theHighest = strDateDigits.first, "12".contains(theHighest) { break }
return false
default: return false
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
var calendar = NSCalendar.current
calendar.timeZone = TimeZone.current
let components = calendar.dateComponents([.day, .month, .year], from: Date())
if let a = calendar.date(from: components), let b = formatter.date(from: dateDigits.description), a == b {
return true
}
return false
}
public static var currentYear: Int {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
return (Int(formatter.string(from: Date())) ?? 1970)
}
}
// MARK: - Tests.
NSLog("start")
print(Date.isTodayTheDate(from: 20230206))
NSLog("end")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment