一尘不染

快速回历(伊斯兰)日历التاريخالهجري

swift

有谁可以帮助我吗

我正在尝试使用Swift语言创建IOS应用,并且我需要使用回历(伊斯兰)日历

我尝试了很多次,但失败了:(

这是我的尝试

    let datenow = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(NSCalendarUnit(UInt.max), fromDate: datenow)

    var gregorian = NSCalendar(identifier:NSIslamicCivilCalendar)
    var date = gregorian.dateFromComponents(components)

    println(date)

并且输出错误

   2576-04-25 09:05:08 +0000

我们是在1434年的回历中,而不是2576年!


阅读 216

收藏
2020-07-07

共1个答案

一尘不染

您正在混合日历,日期和组成部分:

let datenow = NSDate() 
    // This is a point in time, independent of calendars
let calendar = NSCalendar.currentCalendar() 
    // System calendar, likely Gregorian 
let components = calendar.components(NSCalendarUnit(UInt.max), fromDate: datenow) 
    // Gregorian components

println("\(components.year)") // "2014"

var islamic = NSCalendar(identifier:NSIslamicCivilCalendar)! // Changed the variable name 
    // *** Note also NSCalendar(identifier:) now returns now returns an optional ***
var date = islamic.dateFromComponents(components) 
    // so you have asked to initialise the date as AH 2014

println(date) 
    // This is a point in time again, sometime in AH 2014, or AD 2576

您需要做的只是:

let datenow = NSDate()
let islamic = NSCalendar(identifier:NSIslamicCivilCalendar)!
let components = islamic.components(NSCalendarUnit(UInt.max), fromDate: datenow)
println("Date in system calendar:\(datenow), in Hijri:\(components.year)-\(components.month)-\(components.day)")
   //"Date in system calendar:2014-09-25 09:53:00 +0000, in Hijri:1435-11-30"

要获取格式化的字符串,而不仅仅是整数部分,您需要使用NSDateFormatter,这将允许您指定日历和日期以及格式。看这里

更新资料

可以根据要求将数字简单地音译为(东方)阿拉伯数字(因为0
… 9被称为(西方)阿拉伯数字,以区别于罗马数字),您可以使用:

let sWesternArabic = "\(components.day)-\(components.month)-\(components.year)"
let substituteEasternArabic = ["0":"٠", "1":"١", "2":"٢", "3":"٣", "4":"٤", "5":"٥", "6":"٦", "7":"٧", "8":"٨", "9":"٩"]
var sEasternArabic =  ""
for i in sWesternArabic {
    if let subs = substituteEasternArabic[String(i)] { // String(i) needed as i is a character
        sEasternArabic += subs
    } else {
        sEasternArabic += String(i)
    }
}

println("Western Arabic numerals = \(sWesternArabic), Eastern Arabic numerals = \(sEasternArabic)")
2020-07-07