Hassan Joseph Hassan Joseph - 4 months ago 25
Swift Question

Convert gregorian date to Hijri date

The source code comes from:

Hijri (islamic) calendar in swift

How can I convert string date to NSDate?

I just put them together but it has some mistake with the output.

let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "YYYY-MM-DD"

let GregorianDate = dateFormatter.dateFromString("\(Yeartext1.text!)-\(Monthtext1.text!)-\(Daytext1.text!)")

let islamic = NSCalendar(identifier: NSIslamicCalendar)

let components = islamic?.components(NSCalendarUnit(rawValue: UInt.max), fromDate: GregorianDate!)

resultlable.text = "\(components!.year) - \(components!.month) - \(components!.day)"


For example, the user will enter a gregorian date (2015/09/29) and it should show the Hijri year (1436/12/15) but this doesn't work.

Answer

Yeartext1 , Monthtext1 and Monthtext1 are UITextField

resultlable is UILabel

    let dateFormatter = NSDateFormatter()

    dateFormatter.dateFormat = "dd-MM-yyyy"

    let GregorianDate = dateFormatter.dateFromString("\(Daytext1.text!)-\(Monthtext1.text!)-\(Yeartext1.text!)")

    let islamic = NSCalendar(identifier: NSCalendarIdentifierIslamicUmmAlQura)

    let components = islamic?.components(NSCalendarUnit(rawValue: UInt.max), fromDate: GregorianDate!)

    resultlable.text = "\(components!.year) - \(components!.month) - \(components!.day)"

It will take an Gregorian Date 5-10-2015 and it will give you the islamic date 1436 - 12 - 22

*There is a small probability of one day error

you can check this converter http://www.islamicfinder.org/Hcal/hdate_next.php