Format date string as per device locale settings - ios

I have to format the date string (UTC format) as per device locale settings. For example in India it should display as 08/09/2017 12.23 and in US it should display as 09/08/2017 12.23, Based on different region setting it should display the date format accordingly.

The best approach is to not set dateFormat, but rather set dateStyle and timeStyle.
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateStyle = .medium
formatter.timeStyle = .medium
let string = formatter.string(from: Date())
If none of those styles are quite correct, then, go ahead and use dateFormat, but rather than a string literal, set dateFormat using setLocalizedDateFormatFromTemplate(_:).
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.setLocalizedDateFormatFromTemplate("ddMMyyyy HH:mm")
let string = formatter.string(from: Date())
That displays 09/08/2017 19:42 for US users, 08/09/2017 19:42 for United Kingdom users, and 08.09.2017 19:42 for German users

The answer of #Rob above didn't work for me, but it showed the right direction. It turned out the formatterBehavior of the DateFormatter instance wasn't set properly (it defaults to behavior10_4, and not to default. This works for me:
let dateFormatter = DateFormatter()
dateFormatter.formatterBehavior = .default
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
let dateString = dateFormatter.string(from: Date())

Related

How to extract today, yesterday from Date() and make it localised like weekday and months?

I want to extract today, yesterday from date so it is localised automatically when I change language like which happens with weekdays and month.
Code for localised date that I am using:
let dateFormatter = Foundation.DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let dateStr = dateFormatter.string(from: datePickerView.date)
let timeStr = "00:00:00.000"
let dateString = NSString(format:"%# %#",dateStr,timeStr)
let mainDF = Foundation.DateFormatter()
mainDF.dateFormat = "MMMM dd, yyyy hh:mm:ss.SSS"
mainDF.locale = Locale(identifier: "en_US_POSIX")
mainDF.timeZone = TimeZone(identifier: "UTC")
let date = mainDF.date(from: dateString as String)
How to achieve this?
DateFormatter has special flag for that: doesRelativeDateFormatting, which renders dates in relative format, using locale set for this formatter.
… If a date formatter uses relative date formatting, where possible it
replaces the date component of its output with a phrase—such as
“today” or “tomorrow”—that indicates a relative date. The available
phrases depend on the locale for the date formatter; whereas, for
dates in the future, English may only allow “tomorrow,” French may
allow “the day after the day after tomorrow,” …
Example:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent // Using system locale
dateFormatter.doesRelativeDateFormatting = true // Enabling relative date formatting
// other dataFormatter settings here, irrelevant for example
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium
let now = Date()
let dateString: String = dateFormatter.string(from: now)
print("dateString: \(dateString)") // Prints `dateString: <Today in current locale>`

How to change the timeZone in SwiftDate?

I have displayed the list of timezones in my app. If user selects a particular timezones, I need to change the local timezone to the selected timezone by the user.
let region = Region(tz: timeZoneName.timeZone , cal: cal, loc: cal.locale!)
let date = Date().inRegion(region: region).absoluteDate
Here is the problem, the region is changed to the selected timezone but the date issuing the local timezone.
A Date contains no timezone. From apple's docs: A specific point in time, independent of any calendar or time zone.
The timezone comes into play as soon as you want to present a date to the user. And that's what a DateFormatter is for. As #AlexWoe89 already pointed out, it let's you convert a string, containing a date into a Date object, but also lets you convert a given date into a string representing the date in the time zone you set to the timeZone property of DateFormatter.
let date = Date()
var dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
dateFormatter.timeZone = TimeZone(identifier: "America/Los_Angeles")
let dateString1 = dateFormatter.string(from: date)
dateFormatter.timeZone = TimeZone(identifier: "Germany/Berlin")
let dateString2 = dateFormatter.string(from: date)
This will store 2017-10-23 04:27 in dateString1, while the same date leads to 2017-10-23 13:27 in dateString2.
You can use DateFormatter as a solution, try something like this:
let dateString = "<yourDateAsString>"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // => there are a lot of identifiers you can use
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.defaultDate = Date()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm” // => your needed time format
let convertedDate = dateFormatter.date(from: dateString)

Converting UTC to EST in Swift

I have a string of text in my application that conveys a time and the date, such as let time = "2017-07-09T09:17:08+00:00". I want to take this string, which is in UTC, and convert it to a string that presents the time in EST. For my example, the resulting string would be 2017-07-09T05:17:08+00:00. How can this be done?
I've tried using
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone.current
let date = dateFormatter.date(from:time!)!
but printing the date gives me the same time in UTC.
All you need to do is to use a DateFormatter to convert your Date object into a String. By default, the date will be formatted to local time.
// First, get a Date from the String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:time!)!
// Now, get a new string from the Date in the proper format for the user's locale
dateFormatter.dateFormat = nil
dateFormatter.dateStyle = .long // set as desired
dateFormatter.timeStyle = .medium // set as desired
let local = dateFormatter.string(from: date)
Note that there is no need to set any timezone for either set of code in this case.

Date from String with .medium Format

I have a date on a UITextField represented by its .medium formatter style (e.g. Mar 14, 2017), that I want to turn back into date.
I know that if I have the correct format, I can do so, but since I didn't use a literal string as the format, I have a little trouble with the conversion.
I am trying:
let formatter = DateFormatter()
formatter.dateFormat =
//[NEED FORMAT STRING HERE]
calendarPicker.startDate = formatter.date(from: t3.text!)
But I have found no way to turn the .medium style into a string to reformat the string into a date.
Can somebody provide some help?
I've used this formatter with style in Swift 3.0 and it works perfectly fine.
let formatter = DateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
//Specified date format
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
//Style can be medium, full and short as per the need.
formatter.dateStyle = .medium
let parsedDateString = formatter.date(from: stringDate)
Thank you.
Were you looking for dateStyle ?
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
calendarPicker.startDate = formatter.date(from: t3.text!)

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.

Resources