How to convert this string in a date with this format? - swift

Im working with a API, when I ask for a date, this API get my a String like this:
20190717-0300
I want to show that date in a UILabel with this format: "dd '\(preposition)' MMMM"
My attempt was to make a string extension:
extension String {
var toDate: String? {
let dateFormatter = DateFormatter()
let preposition = NSLocalizedString("of", comment: "Preposition of dates formatted")
dateFormatter.dateFormat = "dd '\(preposition)' MMMM"
dateFormatter.locale = Locale.current
if let date = dateFormatter.date(from: self) {
let dateString = dateFormatter.string(from: date)
return dateString
}
return nil
}
}
And then use it:
myLabel.text = thatString.toDate
But .toDate always return nil
Note: The answers I found on the site are cases with ISO format strings.
Expected result:
17 of July

Basically you need an input date format and an output date format.
extension String {
var toDate: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddZ"
if let date = dateFormatter.date(from: self) {
let preposition = NSLocalizedString("of", comment: "Preposition of dates formatted")
dateFormatter.dateFormat = "dd '\(preposition)' MMMM"
let dateString = dateFormatter.string(from: date)
return dateString
}
return nil
}
}
I totally agree with rmaddy's comment to use setLocalizedDateFormatFromTemplate
The source of the date field symbols is unicode.org: Date Format Patterns

Turn this into extension if you like:
// function
func formatDate(_ from:String, preposition:String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddZ"
guard let date = dateFormatter.date(from: from) else {
return nil
}
dateFormatter.dateFormat = "dd '\(preposition)' MMMM"
return dateFormatter.string(from: date)
}
// example usage
let str = "20190717-0300"
if let formatted = formatDate(str, preposition: "of") {
print(formatted)
}

Related

How to reformat a Date to only Year Month and Day? Swift

I'm having trouble reformatting a date to only show .year .monthand .day. The output prints are the same string I input but with hourand minutesshowing zeros and my goal is to only have a string "yyyy-MM-dd"as i'l use it to fetch CoreData for records. If I use that date format Xcode crashes because the incoming date format is "yyyy-MM-dd HH:mm:ssZZZZ". I followed suggested solution from Convert string to date in Swift but is not working in may case. How can a reformat the date?
As always thank you very much.
Here is the function :
func fetchBookings(date : String ) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
// dateFormatter.dateFormat = "yyyy-MM-dd"
let dateFormatted = dateFormatter.date(from:date)!
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.year, .month,.day] , from: dateFormatted)
let dateToCheck = calendar.date(from: components)
let context = CoreData.databaseContext
let fetchRequest = NSFetchRequest<Booking>(entityName: "Booking")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "bookingDate", ascending: true)]
let userPredicate = NSPredicate(format: "user.name == %#", UserDetails.fullName ?? "")
let datePredicate = NSPredicate(format: "bookingDate CONTAINS %#", dateToCheck! as CVarArg)
let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [userPredicate, datePredicate])
fetchRequest.predicate = andPredicate
fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchedResultController.performFetch()
print("##################### selectedDate in fetchBooking() is :\(self.selectedDate) ")
print(" bookings fetched")
print("booking date is: \(date)")
print("dateTocheck is: \(String(describing: dateToCheck!))")
print("today date is : \(Date())")
print("fetched objects are: \(String(describing: fetchedResultController.fetchedObjects))")
} catch {
print("Error fetching bookings :\(error)" )
}
}
Simply create a String extension and
1. convert String to Date with format yyyy-MM-dd HH:mm:ssZZZZ
2. convert Date to String with format yyyy-MM-dd
extension String {
var formattedDate: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
if let date = dateFormatter.date(from: self) {
print(date)
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: date)
}
return nil
}
}
Example:
let dateStr = "2017-04-10 10:33:42GMT"
let formattedDate = dateStr.formattedDate //Output: "2017-04-10"
func getDateWithoutTime(string: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
if let date = dateFormatter.date(from: string) {
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: date)
}
return nil
}
print(getDateWithoutTime1(string:"2019-05-13 12:27:53GMT"))
2019-05-13
Use the below function where you pass the date, the current date format and the required date format.
let dateStr = self.convertDateFormaterCommon(currentFormat: "yyyy-MM-dd HH:mm:ss", reqdFormat: "dd MMM, yyyy", dateStr: myObj.transferDate ?? "")
func convertDateFormaterCommon(currentFormat:String, reqdFormat:String, dateStr: String) -> String
{
if dateStr != ""{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = currentFormat
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from: dateStr)
dateFormatter.dateFormat = reqdFormat
return dateFormatter.string(from: date ?? Date())
}
return ""
}

swift 4 Date from from ISO string to custom format?

I have ISO date from API I want to convert it to another custom date format, I've checked some threads here it's look like I have to use the extension on Date class, unfortunately, all my attempts failed.
this example for date i have :
2014-10-22T00:00:00+00:00
I want to convert it to July 2014
can I use normal Date class to do it?
and below what I am trying to do
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: "2016-08-26T12:39:00Z")
let string = formatter.string(from: Date())
Try it:
let formatter = ISO8601DateFormatter()
if let date = formatter.date(from: "2014-10-22T00:00:00+00:00") {
let string = date.stringDate
print(string) // October 2014
}
extension Date {
var stringDate: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter.string(from: self)
}
}
my Date load from SQL Server and format like this "2018-01-17T03:08:28.158769" the code below is work for me perfectly
let isoDate = "2018-01-17T03:08:28.158769"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
let date = dateFormatter.date(from:isoDate!)!
dateFormatter.dateFormat = "d.MMMM.YYYY"
let displayDate = dateFormatter.string(from: date)
displayDateInLabel.text = displayDate
result
17.January.2018
You can get Month and Year like this
override func viewDidLoad() {
super.viewDidLoad()
print(getFormattedDate(date: Date()))
}
func getFormattedDate(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM YYYY"
let strMonth = dateFormatter.string(from: date)
return strMonth
}

Convert string with timezone to date

I have this type of string and want to convert it to date
"2017-05-27T00:00:00.000+0400"
but none of this formatters convert it to date
"yyyy-MM-dd'T'HH:mm:SSSZ"
"yyyy-MM-dd'T'HH:mm:SSSX"
Your forgot to add ss for seconds so correct formate should be yyyy-MM-dd'T'HH:mm:ss.SSSZ
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2017-05-27T00:00:00.000+0400")
Your error was that the seconds were missing. So the right format should be: yyyy-MM-dd'T'HH:mm:ss.SSSZ. You can also use an extension for this purpose:
extension String {
var toCustomDate: Date {
return Date.Formatter.customDate.date(from: self)!
}
}
extension Date {
struct Formatter {
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}()
}
var customDate: String {
return Formatter.customDate.string(from: self)
}
}
let str = "2017-05-27T00:00:00.000+0400"
let date = str.toCustomDate
If you have more date formats, then just add them to the extensions.
you can do like this
let dateString = "2017-05-27T00:00:00.000+0400"
let formachanger = DateFormatter()
formachanger .dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let dateFromString = formachanger .date(from: dateString) {
formachanger .dateFormat = "yyyy-MM-dd HH:mm"
let stringFromDate = formachanger .string(from: dateFromString)
}
try this function
func getGMTDateFrom(String string : String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss zz"
let dateObj = dateFormatter.date(from: string)
return dateObj
}
Change date format according to your need.

Check the date format of string if it's according to required format or not

I have the same question asked here in Java,
is it possible in swift?
func stringToDate(str: String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
//check validation of str
return date
}
Just same like Java, check if it can parse properly
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
let someDate = "string date"
if dateFormatterGet.date(from: someDate) != nil {
// valid format
} else {
// invalid format
}
For Swift 4 the syntax have changed a bit:
func isValidDate(dateString: String) -> Bool {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
if let _ = dateFormatterGet.date(from: dateString) {
//date parsing succeeded, if you need to do additional logic, replace _ with some variable name i.e date
return true
} else {
// Invalid date
return false
}
}
in swift3 :
func stringToDate(str: String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
guard let date = dateFormatter.date(from: str){
return Date()
}
return date
}
Swift 5
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
let someDate = "string date"
if dateFormatterGet.date(from: someDate!) != nil {
} else {
// invalid format
}

Change date format in Swift

I have a date format in String value of "2015-08-27" which is "YYYY-MM-DD". I need to convert this to Date format and change the format to "DD-MMM-YYYY". And change it back to String format again to display. So the end result would be "27-AUG-2015".
I have been searching for codes, but couldn't find one.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD"
let date = dateFormatter.dateFromString("2015-08-27")
dateFormatter.dateFormat = "DD-MMM-YYYY"
let goodDate = dateFormatter.stringFromDate(date!)
Its not tested but I hope it will work.
You can create a class helper like DateHelper and class func:
class func convertDateString(dateString : String!, fromFormat sourceFormat : String!, toFormat desFormat : String!) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = sourceFormat
let date = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = desFormat
return dateFormatter.string(from: date!)
}
And use it:(note format you give on question wrong so it will wrong convert): begin format is YYYY-MM-dd and you want convert to dd-MMM-YYYY)
print(DateHelper.convertDateString("2015-08-27", fromFormat: "YYYY-MM-dd", toFormat: "dd-MMM-YYYY"))
Hope this help.
Just used the function in your code(swift 4.2).
public func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
print(timeStamp)
return timeStamp
}
Thanks