Swift中的BCE日期

jv4diomz  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(93)

我似乎不知道如何表示BCE日期(BeforeCommonEra /负年),转换似乎总是搞砸了这一年。下面是一些playground代码来显示这个问题:

import Foundation

var date = DateComponents()
date.year = -100
date.month = 1
date.day = 1
date.description
let realDate = Calendar.current.date(from: date)
let components = Calendar.current.dateComponents([.year], from: realDate!)
components.year // Returns 101 !?

我应该如何创建一个有效的BCE日期?最好是从DateComponents,但其他答案也接受!

gjmwrych

gjmwrych1#

我这样做:

extension Date {
    
    static public func from(year : Int? = nil, month : Int? = nil, day : Int? = nil) -> Date? {
        
        //Year 0 is invalid
        if nil != year && year! == 0 {
            return nil
        }
        
        var dateComponents = DateComponents()
        
        dateComponents.month = month
        dateComponents.day = day

        if nil != year {
            //era for BCE = 0, otherwise 1
            dateComponents.era = (year! < 0) ? 0 : 1
            dateComponents.year = (dateComponents.era == 1) ? year : year! * -1
        }

        
        let date = Calendar.current.date(from: dateComponents)
        return date
    }
    
    public func dateParts() -> (year : Int?, month : Int?, day : Int?) {
        
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day, .month, .year, .era], from: self)
        
        var year = components.year
        if components.era == 0 {    //BCE
            if nil != year {
                year = year! * -1
            }
        }

        return (year, components.month, components.day)
    }
}

相关问题