swift – 将currentCalendar()Date转换为NSCalendarIdentifierCh
我已经写了这个函数,以便在过去的100年中在中国历法上获得一年的第一天.从循环返回的一些值是正确的.我已使用此链接
http://www.fengshuimiracle.com/154/how-work-out-your-animal-sign-and-chinese-year验证了中国新年的日期
.是否有可以引用的农历,或者我在代码中遗漏了一些东西. override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. loopthrough() } func returnDateForMonth(month:NSInteger,year:NSInteger,day:NSInteger)->NSDate{ let comp = NSDateComponents() comp.month = month comp.year = year comp.day = day let chCal = NSCalendar(calendarIdentifier: NSCalendarIdentifierChinese) return chCal!.dateFromComponents(comp)! } func showDate(getDate:NSDate)->String{ let date = getDate //let calendar = NSCalendar.currentCalendar() let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierChinese) let dateComponents = calendar!.components([NSCalendarUnit.Year],fromDate: date) let firstDay = returnDateForMonth(dateComponents.month,year: dateComponents.year,day: 1) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd-MMM-yy" let formattedDate = dateFormatter.stringFromDate(firstDay) //print("First day of this month: (formattedDate)") // 01-Sep-15 print(formattedDate) return formattedDate } func substractyear(getI:Int)->String{ let getInt = getI * -1 let components: NSDateComponents = NSDateComponents() components.setValue(getInt,forComponent: NSCalendarUnit.Year); let date: NSDate = NSDate() let expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components,toDate: date,options:NSCalendarOptions(rawValue: 0)) return showDate(expirationDate!) } func loopthrough(){ for var i = 1; i < 100; i++ { //print("(i)") substractyear(i) } } 产量 31-JAN-14 解决方法
我不确定这是否能解答您的问题,但我认为您的代码可以大大简化:
let chineseCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierChinese)! let formatter: NSDateFormatter = { let fmt = NSDateFormatter() fmt.dateStyle = .FullStyle fmt.timeStyle = .MediumStyle fmt.dateFormat = "dd-MMM-yy" return fmt }() var comps = chineseCalendar.components([.Year],fromDate: NSDate()) for _ in 0..<100 { comps.year -= 1 guard let newYear = chineseCalendar.dateFromComponents(comps) else { fatalError("no date for (comps.year)") } print(formatter.stringFromDate(newYear)) } 并且,我不确定您的原始来源是否正确. This page列出了不同的日期(似乎更符合NSCalendar输出). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |