Hijri (islamic) calendar in swift التاريخ الهجري - ios

can someone help me please
I'm trying to create an IOS app using Swift language and I need to use Hijri (islamic) calendar
I tried many time but I failed :(
this is my try
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)
and the output is wrong
2576-04-25 09:05:08 +0000
We are in year 1434 in hijri not 2576 !

You're mixing up the calendars, dates & components:
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
What you need to do is simply:
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"
To get a formatted string, rather than just the integer components, you need to use NSDateFormatter, which will allow you to specify the calendar & date as well as the format. See here.
Update
To simply transliterate the numerals to (Eastern) Arabic numerals (as 0...9 are referred to as (Western) Arabic numerals to distinguish them from, say, Roman numerals), as requested, you could use:
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)")

Get Hajri Date:
Swift :
let dateFor = DateFormatter()
let hijriCalendar = Calendar.init(identifier: Calendar.Identifier.islamicCivil)
dateFor.locale = Locale.init(identifier: "ar") // or "en" as you want to show numbers
dateFor.calendar = hijriCalendar
dateFor.dateFormat = "dd/MM/yyyy"
print(dateFor.string(from: Date()))
Obj-C :
NSCalendar *hijriCalendar2 = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierIslamicCivil];
NSDateFormatter * lastDate = [[NSDateFormatter alloc]init];
lastDate.calendar = hijriCalendar2;
[lastDate setDateFormat:#"dd/MM/yyyy HH:mm:ss"];
NSString * dateString = [lastDate stringFromDate:[NSDate date]];

thank you #Grimxn and I also find a great way to show arabic numbers
let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "ar_SA")
var date:String = "\(formatter.stringFromNumber(components.year))-\(formatter.stringFromNumber(components.month))-\(formatter.stringFromNumber(components.day))"
it will print ١-١١-١٤٣٤

Swift 3 & 4
let dateNow = DateFormatter()
let islamicCalendar = Calendar.init(identifier: Calendar.Identifier.islamicCivil)
dateNow.calendar = islamicCalendar
dateNow.locale = Locale.init(identifier: "ar_SA") // This is used to show numbers, day and month in arabic letters
dateNow.dateFormat = "EEE dd MMM yyyy"
print("\(dateNow.string(from: Date()))")
find out and place date format from:
http://userguide.icu-project.org/formatparse/datetime

Swift 5:
let hijriCalendar = Calendar(identifier: .islamicCivil)
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "ar")
formatter.calendar = hijriCalendar
formatter.dateFormat = "dd/MM/yyyy"
print(formatter.string(from: Date()))

Related

dateFormatter returns wrong date with two digit year specifier [duplicate]

For date Input "00/02/02"
formating Style is yy/MM/dd
I am getting correct output like 02/01/2000
But issue is when trying with "00/01/01"
getting output like this '01/01/12100'
But I don't know why this year coming like 12100
My code is
let str = "00/01/01"
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yy/MM/dd"
if let showDate = inputFormatter.date(from: str) {
inputFormatter.dateFormat = "dd/MM/yyyy"
let resultString = inputFormatter.string(from: showDate)
print(resultString)
}
year input type always as yy format.
As per the #MartinR suggestion
settinginputFormatter.defaultDate to current date or Date(timeIntervalSinceReferenceDate: 0) its worked fine
let str = "00/01/01"
let inputFormatter = DateFormatter()
inputFormatter.defaultDate = Date(timeIntervalSinceReferenceDate: 0)
inputFormatter.dateFormat = "yy/MM/dd"
if let showDate = inputFormatter.date(from: str) {
inputFormatter.dateFormat = "dd/MM/yyyy"
let resultString = inputFormatter.string(from: showDate)
print(resultString)
}
I managed to reproduce this bug by setting the timezone of the formatter, before getting the date from it, to your local timezone:
inputFormatter.timeZone = TimeZone(identifier: "Asia/Kolkata")
//Or
inputFormatter.timeZone = TimeZone(identifier: "Asia/Calcutta")
They both lead to 01/01/12100.
Actually, using a date format of yy/MM/dd hh:mm:ss, all dates starting from 00/01/01 00:00:00 to 00/01/01 05:29:59 give a year component of 12100. This is due to the time zone of Kolkata being offset by +05H30 from GMT. This is a bug.
Setting the timezone to UTC yields the desired output:
inputFormatter.timeZone = TimeZone(identifier: "UTC") //01/01/2000
This bug occurs with other timezones too:
inputFormatter.timeZone = TimeZone(identifier: "Africa/Addis_Ababa")
inputFormatter.timeZone = TimeZone(identifier: "Europe/Moscow")
inputFormatter.timeZone = TimeZone(identifier: "Asia/Hong_Kong")
Basically all timezones that have GMT + hh:mm

Swift how to convert string to NSDate

I've got a date stored in my database and I want to retrieve it and display it nicely in my tableview cells.
The format it comes in from the database and stored in option1 is BO05151530
Where the first two letters have meaning in the program but are not needed for the date so I take those off using the substringFromIndex function.
So what is left is 05151530 where it represents MMddhmm
I would like to display it nicely like MM-dd # h:mm a
For example 12-05 # 3:45 am
Here is what I tried but unfortunately ns_date1 comes up as nil each time.
What would you suggest I do?
let date1 = option1.substringFromIndex(option1.startIndex.advancedBy(2))
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMddhhmm"
let ns_date1 = dateFormatter.dateFromString(date1)
Try this. you don't need to separate BO NSDateFormatter can handle extra string
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "'BO'MMddHHmm"
let ns_date1 = dateFormatter.dateFromString("BO05151530")
dateFormatter.dateFormat = "'BO' MM-dd # hh':'mm a"
let string = dateFormatter.stringFromDate(ns_date1!)
try
dateFormatter.dateFormat = "MMddHHmm"
HH is 24 hour format and hh is 12 hour format. you need the 24 one
Check out this app, this will help you know the right format and give you code
https://itunes.apple.com/ae/app/date-format-creator/id965645209?mt=12
NOTE: you need to add year to get a correct NSDate
I have this function :
class func getTheDateString(stringForInputDate: String, fromFormat inputFormat: String, toFormat outputFormat: String) -> String {
let formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = inputFormat
formatter.timeZone = NSTimeZone.localTimeZone()
let dateForInput: NSDate = formatter.dateFromString(stringForInputDate)!
formatter.dateFormat = outputFormat
return formatter.stringFromDate(dateForInput)
}
and used it as:
let stringDate : String = "0515930" // "05151530"
if stringDate.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) < 8 {
print([ViewControllerForScreen1 .getTheDateString(stringDate, fromFormat: "MMddHmm", toFormat: "MM-dd # h:mm a")]);
}else {
print([ViewControllerForScreen1 .getTheDateString(stringDate, fromFormat: "MMddHHmm", toFormat: "MM-dd # h:mm a")]);
}
OUTPUT:
["05-15 # 9:30 AM"]
["05-15 # 3:30 PM"]

how to convert english date to arabic date ios swift

in my app i am getting date in this format = "2016-02-15 10:49:59" bu i want to display it in this format "الأربعاء, 9 مارس, 2016 10:33 ص" so how can i do this?
i mage showing the format in which i want iot
You can make use of NSDateFormatter and locale "ar_DZ", with a custom format specification to fit your needs: "EEEE, d, MMMM, yyyy HH:mm a".
// input date in given format (as string)
let inputDateAsString = "2016-03-09 10:33:59"
// initialize formatter and set input date format
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// read input date string as NSDate instance
if let date = formatter.dateFromString(inputDateAsString) {
// set locale to "ar_DZ" and format as per your specifications
formatter.locale = NSLocale(localeIdentifier: "ar_DZ")
formatter.dateFormat = "EEEE, d, MMMM, yyyy HH:mm a"
let outputDate = formatter.stringFromDate(date)
print(outputDate) // الأربعاء, 9 مارس, 2016 10:33 ص
}
Note that the above uses the default gregorian calendar (in so not translating e.g. year 2016 to year 1437 (/1438 ~October 2016) in the islamic calendar).
(Edit addition regarding your comment below)
If you change localeIdentifier above from "ar_DZ" to "ar", also numeric values gets written in arabic characters:
print(outputDate) // الأربعاء, ٩ مارس, ٢٠١٦ ١٠:٣٣ ص
However, I don't know arabic, so I can't really say if your image above displays that, and I'm no longer certain what you're trying to achieve; possibly this is not it.
Check this
let morningOfChristmasComponents = NSDateComponents()
morningOfChristmasComponents.year = 2014
morningOfChristmasComponents.month = 12
morningOfChristmasComponents.day = 25
morningOfChristmasComponents.hour = 7
morningOfChristmasComponents.minute = 0
morningOfChristmasComponents.second = 0
let morningOfChristmas = NSCalendar.currentCalendar().dateFromComponents(morningOfChristmasComponents)!
/***** NSDateFormatter Part *****/
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
formatter.locale = NSLocale(localeIdentifier: "ar")
let dateString = formatter.stringFromDate(morningOfChristmas)
txtMarks.text = dateString
For solving of youre issue try to use legend way with NSCalendar style:
var today = NSDate()
let islamic = NSCalendar(identifier:NSCalendarIdentifierIslamicCivil)!
let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
formatter.timeStyle = .MediumStyle
formatter.calendar = islamic
formatter.locale = NSLocale(localeIdentifier: "ar_DZ")
formatter.stringFromDate(today) // "30 جمادى الأولى، 1437 هـ، 11:22:10 ص"
To configure proper style set yore's dateStyle and timeStyle also set up youre NSLocale.

how to work with UIDatePicker in Swift?

I built a UI that has 3 UIDatePicker
The first UIDatePicker named date will be for Date only (Mode .Date)
Other UIDatePickers names time_from and time_to will be for Time (From time, To time) (Mode .Time)
Then I add a Button,
When I click the button I need to get two variables:
From_DateTime and To_DateTime
(I need the Date from date UI and the time from time_from, time_to
I try a lot but without the desired result:
let date = date.calendar
let date_components = date.components(.Calendar, fromDate: date.date)
let date_from_components = dateFrom.calendar.components(.Calendar, fromDate: dateFrom.date)
let date_to_components = dateTo.calendar.components(.Calendar, fromDate: dateTo.date)
let n = date.calendar.dateBySettingHour(date_from_components.hour, minute: date_from_components.minute, second: 5, ofDate: dateFrom.date, options: NSCalendarOptions.MatchStrictly)
This is an example of fails trying.
I need a simple way to get From_DateTime and To_DateTime
Thanks
Finally I found a way:
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "US")
dateFormatter.dateFormat = "yyyy-MM-dd"
let timeFormatter = NSDateFormatter()
timeFormatter.locale = NSLocale(localeIdentifier: "US")
timeFormatter.dateFormat = " HH:mm"
let date_from = dateFormatter.stringFromDate(date.date) + timeFormatter.stringFromDate(dateFrom.date)
let date_to = dateFormatter.stringFromDate(date.date) + timeFormatter.stringFromDate(dateTo.date)
I am sure there must be another simple way.

Mismatch between String Date and NSDate through dateFromString in XCode

I am having an issue with converting a string to NSDate in Xcode: I am trying to get the current date, subtract one day and set the hour to noon. This is how I'm going about it (thw two snippets are in different functions):
let date = NSDate();
let dateFormatter = NSDateFormatter()
//var locale = NSLocale(localeIdentifier: "en_US_POSIX")
//dateFormatter.locale = locale
dateFormatter.dateFormat = "dd/mm/yyyy HH:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
var string = dateFormatter.stringFromDate(date)
var localdate = dateFormatter.dateFromString(string)
var localString = dateFormatter.stringFromDate(localdate!)
var calendar = NSCalendar.currentCalendar()
var components = calendar.components(NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.YearCalendarUnit, fromDate: localdate!)
self.dateCriteriaHour = components.hour
self.dateCriteriaDay = components.day
self.dateCriteriaMonth = components.month
self.dateCriteriaYear = components.year
This seems to work: I get the current date's components. Then I do this:
var day = String(self.dateCriteriaDay - 1)
var month = String(currentMonth)
var year = String(self.dateCriteriaYear)
var hour = "12:00"
var date = year + "/" + month + "/" + day + " " + hour
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/m/dd HH:mm"
var criteriaDate = dateFormatter.dateFromString(date)
println(date)
println(NSDate())
println(criteriaDate)
This is where things get strange. Here is the output to the console:
2015/7/11 12:00
2015-07-12 15:21:42 +0000
Optional(2015-01-11 04:00:00 +0000)
I understand that the device stores time in its selected time zone so I'm not too worried about that. What puzzles me is basically that everything is right except for the month, even though it comes out right in the string.
Any idea as to why this is happening?
Your dateformat is wrong.
dd/mm/yyyy HH:mm
^^ ^^
You use mm two times. A lower case m means minutes, an upper case M means month. So your dateFormat should be dd/MM/yyyy HH:mm

Resources