Swift 4:验证信用卡的到期日期

时间:2019-05-31 05:36:34

标签: swift date

我正在编写代码以检查信用卡是否已过期。

这就是我所拥有的

[10, 50, 105, 232]

关于如何将初始化日期更改为每月的最后一天而不是第一天的任何想法?

6 个答案:

答案 0 :(得分:1)

enteredDate将是到期日期当月第一天的当地时间午夜。由于您希望整个月都有效,因此请在该值上加上1个月,然后将Date()与该更新后的值进行比较。

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!)!
let endOfMonth = Calendar.current.date(byAdding: .month, value: 1, to: enteredDate)!
let now = Date()
if (endOfMonth < now) {
    print("Expired - \(enteredDate) - \(endOfMonth)")
} else {
    // valid
    print("valid - now: \(now) entered: \(enteredDate)")
}

请注意,我留给读者适当的可选操作处理。

答案 1 :(得分:0)

m-m

因为这仅比较月份和年份,所以它将解决您的月份的第一天或最后一个日期。

答案 2 :(得分:0)

rmaddy's答案是完美的。这就是我想到的使用Calendar处理验证的方式。也许,我用更复杂的方式写了它。

enum ExpiryValidation {
    case valid, invalidInput, expired
}

func validateCreditCardExpiry(_ input: String) -> ExpiryValidation {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/yyyy"

    guard let enteredDate = dateFormatter.date(from: input) else {
        return .invalidInput
    }
    let calendar = Calendar.current
    let components = Set([Calendar.Component.month, Calendar.Component.year])
    let currentDateComponents = calendar.dateComponents(components, from: Date())
    let enteredDateComponents = calendar.dateComponents(components, from: enteredDate)

    guard let eMonth = enteredDateComponents.month, let eYear = enteredDateComponents.year, let cMonth = currentDateComponents.month, let cYear = currentDateComponents.year, eMonth >= cMonth, eYear >= cYear else {
        return .expired
    }
    return .valid
}

let invalidInput = validateCreditCardExpiry("hello")
let validInput = validateCreditCardExpiry("09/2020")
let expiredInput = validateCreditCardExpiry("04/2010")

答案 3 :(得分:0)

与其比较日期,不如使用compare(_:to:toGranularity:)

比较日期的月份。
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
if let enteredDate = dateFormatter.date(from: "05/2019") {
    let result = Calendar.current.compare(Date(), to: enteredDate, toGranularity: .month)
    if result == .orderedSame {
        print("valid")
    } else if result == .orderedAscending {
        print("valid")
    } else if result == .orderedDescending {
        print("expired")
    }
}

答案 4 :(得分:0)

这是格式为MM / YY的文本字段中的到期日计算的完整答案。在textfield中使用此字段应更改字符范围方法

var cleanString = string.replacingOccurrences(of: "/", with: "")
    
    if cleanString.rangeOfCharacter(from: unsupportedCharacterSet) != nil {
        return ""
    }
    
    let dateString: String
    
    if cleanString.count == 0 {
        return string
    } else if cleanString.count > 4 {
        // trim the string down to 4
        
        let reqIndex = cleanString.index(cleanString.startIndex, offsetBy: 4)
        cleanString = String(cleanString[..<reqIndex])
        
    }
    
    if cleanString.hasPrefix("0") == false && cleanString.hasPrefix("1") == false {
        dateString = "0" + cleanString
    } else {
        dateString = cleanString
    }
    let currentYear = Calendar.current.component(.year, from: Date()) % 100   // This will give you current year (i.e. if 2019 then it will be 19)
      let currentMonth = Calendar.current.component(.month, from: Date()) // This will give you current month (i.e if June then it will be 6)
    var newText = ""
    for (index, character) in dateString.enumerated() {
        print("index: \(index)")
        if index == 1 {
            let enterdMonth = Int(dateString.prefix(2)) ?? 0  // get first two digit from entered string as month
            print("enterdMonth at 1:\(enterdMonth)")
            if (1 ... 12).contains(enterdMonth){
                if enterdMonth < 10 {
                    newText = "0" + "\(enterdMonth)" + "/"
                }else {
                    newText = "\(enterdMonth)" + "/"
                }
            }else{
                
            }
        }else if index == 2 {
            if (2 ... 99).contains(Int(String(character))!) { // Entered year should be greater than 2019.
                newText.append(character)
            }else{
                
            }
        }else if index == 3 {
            print("index---: \(index)")
            let enterdYr = Int(dateString.suffix(2)) ?? 0   // get last two digit from entered string as year
            let enterdMonth = Int(dateString.prefix(2)) ?? 0  // get first two digit from entered string as month
            print("enterdYr: \(enterdYr)")
            print("currentYear: \(currentYear)")
            if (2 ... 99).contains(enterdYr) { // Entered year should be greater than 2019
                if enterdYr >= currentYear {
                    if (1 ... 12).contains(enterdMonth) {
                        if enterdMonth < 10 {
                            newText = "0" + "\(enterdMonth)" + "/" + "\(enterdYr)"
                        }else {
                            newText = "\(enterdMonth)" + "/" + "\(enterdYr)"
                        }
                        return newText
                    }
                }
            }
        }
        else {
            newText.append(character)
        }
    }
    return newText
}

答案 5 :(得分:-1)

if enteredDate.compare(now) == ComparisonResult.orderedDescending
        {
            print("valid")
        }
else{
      print("not valid")
}