9

How can I convert Gregorian datepicker to persian datepicker in Swift language ?

func datePickerValueChanged(sender: UIDatePicker) {

    let dateFormatter = NSDateFormatter()

    dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle

    dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
    dateFormatter.dateFormat = NSCalendarIdentifierPersian

    dateOutlet.text = dateFormatter.stringFromDate(sender.date)

}

I changed date format toNSCalendarIdentifierPersian but there isnt any change in datepicker?

3 Answers3

12

You need to set the calendar, not the dateFormat:

dateFormatter.calendar = NSCalendar(identifier: NSCalendarIdentifierPersian)

You would also have to set the locale property if you want the language to change:

dateFormatter.locale = NSLocale(localeIdentifier: "fa_IR")

Also, as the comment on the question notes, you're working with an NSDateFormatter, not a UIDatePicker in your code. Fortunately the answer is still correct; UIDatePicker also has a calendar property that you would set to accomplish this goal.

Charles A.
  • 10,685
  • 1
  • 42
  • 39
  • thanks for answering I understand and add calendar to my dateickerView, its worked but language of datepicker is not change to persian is there any way to change language? – Mohammad Alikhani Oct 27 '15 at 19:09
  • 1
    Is your device in persian? It should show in whatever locale the device/simulator is set to. If you want to override the device/simulator locale, you have to set the `locale` property. I will update my code example. – Charles A. Oct 27 '15 at 20:25
  • 1
    Apple does not support persian language, so there is no way to use persian as locale. – Fa.Shapouri Jan 24 '17 at 20:47
  • can i set globally. my app is old and I have big project.. and I have used calendar so many places. – Maulik shah Jun 30 '20 at 08:16
  • I don't think there is a way to change the default locale to something that isn't what the device is set to. Your best bet is probably to make a function (perhaps in an extension on Calendar if you're using Swift) that creates the calendar and sets its locale and use that everywhere you ned it. – Charles A. Jul 01 '20 at 15:31
4

SwiftUI Sample :

 DatePicker("", selection: self.$mySelectionDate, displayedComponents: .date)
                        .environment(\.locale, Locale.init(identifier: "fa_IR"))
                        .environment(\.calendar,Calendar(identifier: .persian))
Farshid roohi
  • 722
  • 9
  • 23
3

Swift 3:

As Charles A. Said DatePicker has a calendar property and you can use it to have persian datepicker or even :

datePicker.calendar = Calendar(identifier: .persian)
datePicker.locale = Locale(identifier: "fa_IR")
Reza Dehnavi
  • 2,256
  • 3
  • 16
  • 30
Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78