Date from String with .medium Format - ios

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!)

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>`

Format date string as per device locale settings

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())

Parsing date string coming from Fitbit API

For the life of me I cannot figure out how to convert date string coming back from the Fitbit API, to an NSDate/Date object on iOS.
The date string is in the following format:
2017-01-21T10:39:43.000
The API I am using is documented here: https://dev.fitbit.com/docs/devices/, and each device comes back with a "lastSyncTime" property in the JSON.
I've tried several different date formats that keep returning a nil value for the date.
let formatter = DateFormatter()
// formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
// formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
// formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
// formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssz"
// formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSz"
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: lastSyncTime)
I've tried all these different date formats to no avail.
Any help would be greatly appreciated here. Thanks.
Use this formatter to parse it.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
formatter.date(from: dateString)
I hope this helps
This works for me:
import Foundation
let date = "2017-01-21T10:39:43.000"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let formatDate = formatter.date(from: date)
print(formatDate!)
Output: 2017-01-21 16:39:43 +0000

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.

Swift dateFormat for variable dateType strings

I am trying to parse some json which is the result of an oData connection and I am getting the following response from the server:
"Task_ID":24,"Equipment_ID":3,"Owner_ID":2,"Priority":5,"Date_Due":
"2015-04-08T19:37:56.913","Time_Complete":"2015-04-09T19:37:56","Task_Description"
I am actually interested at the two different date fields I am receiving:
"Date_Due":"2015-04-08T19:37:56.913"
and
"Time_Complete":"2015-04-09T19:37:56"
As we can see, one has the millisecond timestamp and the other one does not.
By looking at the DB, this happens because the millisecond is actually .000 in the database (MS SQL Server) and for whatever reason, the result I receive in my json has this part truncated.
I am not interested in the milliseconds but I would like to have a dateFormat function that can handle both scenarios.
Now I have an obvious answer which is (pre)parse every date field, remove the milliseconds if they are there and then use the following code to format them:
let SQLDateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return formatter
}()
However I would like to know if we can build a formatter that can solve this issue without pre-parsing, something that would be able to take both:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
and
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
and automatically do the formatting properly.
I have been checking for this issue but could not find anything out there, thanks in advance...
extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
static let iso8601withFractionalSeconds: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
}
extension String {
var date: Date? {
return Formatter.iso8601withFractionalSeconds.date(from: self) ??
Formatter.iso8601.date(from: self)
}
}
"2015-04-08T19:37:56.913".date // "Apr 8, 2015, 4:37 PM"
"2015-04-09T19:37:56".date // "Apr 9, 2015, 4:37 PM"
No, NSDateFormatter will return nil if the string is not in the exact dateFormat as specified.
What you can do instead of preprocessing the string, is just check if the string you got is with miliseconds or without.
The best way to do this is using Regex. The idea is to create the SQLDateFormatter like you normal, and then check if the string has miliseconds or not. If there are miliseconds included, just change the dateFormat - way better than parsing the string.
if let match = tes.rangeOfString("(\\d{4}-\\d\\d-\\d\\d[T](\\d\\d:){2}\\d\\d.\\d{3})", options: NSStringCompareOptions.RegularExpressionSearch)
{
SQLDateFormatter.format = "yyyy-MM-dd'T'HH:mm:ss.SSS"
}

Resources