初始化日期变量并计算年龄

问题描述 投票:0回答:1

我的项目中有以下数据结构。 基本上我有两个无法设置的变量:

import Foundation

struct Rosa: Identifiable, Hashable, Equatable {
    let id = UUID()
    let stagione: String
    let nomeGiocatore: String
    let cognomeGiocatore: String
    let nascitaGiocatore: Date
    let etàGiocatore: Int
    let ruoloGiocatore: String
    
    init(stagione: String, nomeGiocatore: String, cognomeGiocatore: String, nascitaGiocatore: Date, etàGiocatore: Int, ruoloGiocatore: String) {
        self.stagione = stagione
        self.nomeGiocatore = nomeGiocatore
        self.cognomeGiocatore = cognomeGiocatore
        self.nascitaGiocatore = nascitaGiocatore
        self.etàGiocatore = etàGiocatore
        self.ruoloGiocatore = ruoloGiocatore
        
        nascitaGiocatore.formatted(date: .numeric, time: .omitted)
    }
    
    static func testRosa() -> [Rosa] {
        [Rosa(stagione: "2023/2024", nomeGiocatore: "Matt", cognomeGiocatore: "Bar", nascitaGiocatore: 03/31/2000, etàGiocatore: 23, ruoloGiocatore: "Portiere")]
    }
}

我想要“nascitaGiocatore”格式为“dd-MM-YYYY”和“etàGiocatore”作为当前年份和“nascitaGiocatore”年份之间的差异。 但我完全被困住了。

swift date
1个回答
0
投票

您可以使用 DateFormatter 来解析 testRosa 方法中的出生日期字符串。它应该像下面这样:

static func testRosa() -> [Rosa] {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        let birthDate = dateFormatter.date(from: "31-03-2000")!
        
        let currentYear = Calendar.current.component(.year, from: Date())
        let birthYear = Calendar.current.component(.year, from: birthDate)
        let age = currentYear - birthYear
        
        return [Rosa(stagione: "2023/2024", nomeGiocatore: "Matt", cognomeGiocatore: "Bar", nascitaGiocatore: birthDate, etàGiocatore: age, ruoloGiocatore: "Portiere")]
    }

您也不需要格式化“nascitaGiocatore”。这似乎没有必要。您可以删除它。

© www.soinside.com 2019 - 2024. All rights reserved.