Swift: Convert Array of String dates into Formatted String dates - swift

So I have an array of dates that are already formatted as strings. But I want to further format it. What I have currently prints me nil. I want to be able to convert it into something like "June, 23, 2020" or "June-23", etc. What am I missing?
let dates = ["2020-06-23", "2021-06-24", "2022-06-25", "2020-06-26", "2020-06-29"]
for i in dates {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd"
let date = dateFormatter.date(from: i)
print(date)
}

First you get the right format. Then you can change it.
You can use
let dates = ["2020-06-23", "2021-06-24", "2022-06-25", "2020-06-26", "2020-06-29"]
//create an empty array of dates
var datesFormated = [Date]()
let initialDateFormatter = DateFormatter()
initialDateFormatter.dateFormat = "yyyy-MM-dd"
for i in dates {
let date = initialDateFormatter.date(from: i)!
//but you have to make sure that the date format of the strings match the date formatter, otherwise it will crash
datesFormated.append(date)
}
//then change the format to the one you need
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy"
for date in datesFormated {
let date = dateFormatter.string(from: date)
print(date)
}
Output would be
Jun 23, 2020
Jun 24, 2021
Jun 25, 2022
Jun 26, 2020
Jun 29, 2020
Hope this helps.

Try with:
let dates = ["2020-06-23", "2021-06-24", "2022-06-25", "2020-06-26", "2020-06-29"]
var datesFormated = [Date]()
let initialDateFormatter = DateFormatter()
let dateFormatter = DateFormatter()
initialDateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.dateFormat = "MMM d, yyyy"
dates.forEach {
datesFormated.append( initialDateFormatter.date(from: $0)! )
}
datesFormated.forEach {
print(dateFormatter.string(from: $0))
}
Output:
Jun 23, 2020
Jun 24, 2021
Jun 25, 2022
Jun 26, 2020
Jun 29, 2020

I was writing this as you posted your answer, but I'll post anyway as there's a slight difference in approaches.
I suggest using both DateFormatter.date(from: string) AND DateFormatter.string(from: date). In other words, build two distinct date formatters: one to read in your date in "yyyy-MM-DD" format, and another to make a string in a different format. You can then change each of the formatters as needed, or even have a method wrapping this code where you can insert different formatters or format strings, making it flexible if you want to change formats.
Also, there's no need to instance a new formatter every time you go through the loop.
let dates = ["2020-06-23", "2021-06-24", "2022-06-25", "2020-06-26", "2020-06-29"]
// use this formatter to read in dates from initial strings
let originalDateFormatter = DateFormatter()
originalDateFormatter.dateFormat = "yyyy-MM-dd"
// use this formatter to generate new strings from dates
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMMM d" // or choose whatever new string format you want
for i in dates {
if let date: Date = originalDateFormatter.date(from: i) {
let dateInNewStringFormat: String = newDateFormatter.string(from: date)
print(dateInNewStringFormat) // prints as "June 23"
}
}

First of all, initializing DateFormatter on every iteration is very wasteful. Make it constant or static, and only change format when needed.
Secondly, when working with DateFormatter, you should always think of it as transformation where date to string, or vice versa, but you cannot transform one string to another directly. In your case, you need:
string > date > string
So basic code would look like this:
let dates = ["2020-06-23", "2021-06-24", "2022-06-25", "2020-06-26", "2020-06-29"]
let dateFormatter = DateFormatter()
for i in dates {
// string > date
dateFormatter.dateFormat = "YYYY-MM-dd"
guard let fromDate = dateFormatter.date(from: i) else {
// not a valid date, skip
continue
}
// date > string
dateFormatter.dateFormat = "MMM, YYYY" // or whatever you need
let toDate = dateFormatter.string(from: fromDate)
print(toDate)
}
But also, if you have this same formatting in multiple places in your code, it's best to create an extension:
extension Date {
static let dateFormatter = DateFormatter()
// If you are dealing with the same date as input often, you can do this:
init?(fromDateOnlyString: String) {
Date.dateFormatter.dateFormat = "YYYY-MM-dd"
guard let date = Date.dateFormatter.date(from: fromDateOnlyString) else {
return nil
}
self = date
}
// If you need the same output format often, you can do this:
func toMyDesiredFormat() -> String {
Date.dateFormatter.dateFormat = "MMM, YYYY" // Or whatever you need
return Date.dateFormatter.string(from: self)
}
}
And you use this extension like this:
for i in dates {
guard let fromDate = Date(fromDateOnlyString: i) else {
// not a valid date, skip
continue
}
let toDate = fromDate.toMyDesiredFormat()
print(toDate)
}

Found the solution. You have you first convert it into Dates then convert those Dates into Formatted strings again. I had the format for the initial dateFormatter wrong as "dd".
let dates = ["2020-06-23", "2020-06-24", "2020-06-25", "2020-06-26", "2020-06-29"]
var formattedDates = [Date]()
for i in dates {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = dateFormatter.date(from: i) {
formattedDates.append(date)
}
}
print(formattedDates) //prints [2020-06-23 04:00:00 +0000, 2020-06-24 04:00:00 +0000, 2020-06-25 04:00:00 +0000, 2020-06-26 04:00:00 +0000, 2020-06-29 04:00:00 +0000]

Related

Getting error when converting date format error | Swift

Essentially I would like to convert the following:
2022-07-01 14:35:00
To simply:
July 1st
The following is what I currently have because the initial input is string, but when I'm converting from string to date time the hour seems to have +2 hours added to it. Why is this happening?
// Create String
let string = "2022-07-01 14:35:00"
// Create Date Formatter
let dateFormatter = DateFormatter()
// Set Date Format
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// Convert String to Date
let newdate = dateFormatter.date(from: string)
print(newdate!)
Time depends on where you are. So in this case the +2 hours you see, may be due to the difference in TimeZone. So adjust the TimeZone in the format to match the original place, or put everything in GMT TimeZone, or a common TimeZone of your choosing. Alternatively, keep the time difference.
Try something like this:
let string = "2022-07-01 14:35:00"
let readFormatter = DateFormatter()
readFormatter.timeZone = TimeZone(abbreviation: "GMT") // <-- here adjust
readFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let writeFormatter = DateFormatter()
writeFormatter.timeZone = TimeZone(abbreviation: "GMT") // <-- here adjust
writeFormatter.dateFormat = "LLLL dd"
if let theDate = readFormatter.date(from: string) {
print("\n----> theDate: \(theDate)") // ----> theDate: 2022-07-01 14:35:00 +0000
let simpleDate = writeFormatter.string(from: theDate)
print("\n----> simpleDate: \(simpleDate)") // ----> simpleDate: July 01
}

Date format from url (JSON)

How would I be able to take the date format from a URL and turn It into 2 separate date values in SwiftUI. The format from JSON is 2019-11-06 18:30:00 and I'm trying to get it to show as Dec 5 and would also like it to separate the time and show 8:00PM, is this possible?
This is the code that references the start time:
let startTime: String
var startTime: String {
return self.post.startTime
}
Let's step around the fact that 2019-11-06 18:30:00 can't be represented as Dec 5 and 8:00PM and focus on the work flow you'd need.
The basic idea is to:
Convert the String to a Date, via a DateFormatter
Use a custom DateFormatter to format the Date to the required "date" value
Use a custom DateFormatter to format the Date to the required "time" value
This might look something like...
let startTime = "2019-11-06 18:30:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = formatter.date(from: startTime) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d"
let dateString = dateFormatter.string(from: date)
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "h:ma"
let timeString = timeFormatter.string(from: date)
} else {
print("Bad date/format")
}
In my testing, this outputs Nov 6 and 6:30PM
you can pass your string date to date with this function
func stringToDate(date: String, format: String) -> Date
{
let date2 = date.count == 0 ? getCurrentDate(format: "dd-MM-yyyy") : date
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.init(identifier: "América/Mexico_City")
dateFormatter.dateFormat = format
let dateDate = dateFormatter.date(from: date2)
return dateDate!
}
func getCurrentDate(format: String) -> String
{
let formD = DateFormatter()
formD.dateFormat = format
let str = formD.string(from:Date())
return str
}
let dateA = stringToDate(date: "2019-11-06 18:30:00", format: "yyyy-MM-dd HH:mm:ss")
if dateA < Date() //Date() always will be the current date, including the time
{
print("dateA is older")
}
else
{
print("dateA in newer")
}
play with the format examples formats

Date (String) to Date (ISO) at Swift

I am aware about similar questions, however, I couldn't find this exact one:
In an iOS application, I am receiving a date in the format dd-MM-yyyy HH:mm:ss (i.e. 30-07-2019 12:05:00) in GMT +2h, and I like to convert it to yyyy-MM-dd HH:mm:ss +0000 in GMT ±0h (i.e. 2019-07-30 10:05:00 +0000).
How can I do this?
Firstly create 2 DateFormatter.
First dateFormat for create date from dateString.
Second dateFormat for create string from created date.
Code:
let dateString = "30-07-2019 12:05:00"
let dateFormatForDate = DateFormatter()
dateFormatForDate.timeZone = TimeZone(abbreviation: "GMT+2")
dateFormatForDate.dateFormat = "dd-MM-yyyy HH:mm:ss"
//date
let date = dateFormatForDate.date(from: dateString)
let dateFormatForString = DateFormatter()
dateFormatForString.timeZone = TimeZone(abbreviation: "GMT")
dateFormatForString.dateFormat = "yyyy-MM-dd HH:mm:ss +0000"
//string
let formattedDateString = dateFormatForString.string(from: date!)
Result:
dateString: 30-07-2019 12:05:00
formattedDateString: 2019-07-30 09:05:00 +0000
extension Date {
func convert(_ from: TimeZone, toTimeZone: TimeZone) -> Date {
let delta = TimeInterval(toTimeZone.secondsFromGMT() - from.secondsFromGMT())
return addingTimeInterval(delta)
}
}
let dateFmt = DateFormatter()
dateFmt.timeZone = TimeZone(abbreviation: "GMT+2")
dateFmt.dateFormat = "dd-MM-yyyy HH:mm:ss"
if let date = dateFmt.date(from: "30-07-2019 12:05:00") {
let localDate = date.convert(TimeZone(abbreviation: "GMT+02")!, toTimeZone: TimeZone(abbreviation: "GMT+00")!)
}

Converting string to date returning the day before

I have a date in a string with this format "2017-03-14" (yyyy-MM-dd) and i am trying to convert it into a string with this format "Tuesday, March 14, 2017".
This is my code:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2017-03-14")
Now if i print the value of "date", i get this:
2017-03-13 22:00:00 +0000
This is just the day before. Why is that ?
EDIT:
I need to compare date before formatting it.
var newDateString : String = ""
let date2 = Date()
let comp = date2.compare(date!)
if comp.rawValue == 0 {
newDateString = "TONIGHT"
} else {
dateFormatter.dateFormat = "EEEE, MMMM d, yyyy"
newDateString = dateFormatter.string(from: date!)
}
Thanks
The desired Format should be:
EEEE, MMMM dd, yyyy
All you have to do is to add after your code the following code snippet:
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
let string = dateFormatter.string(from: date!) // "Tuesday, March 14, 2017"
Remark:
I'd like to suggest to do optional binding for declaring the date, as follows:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = dateFormatter.date(from: "2017-03-14") {
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
let string = dateFormatter.string(from: date) // "Tuesday, March 14, 2017"
}
Your confusion is based on a misunderstanding of what Time and Date are. Evidently, you are currently located in a time zone that is 2 hours ahead of UTC (Coordinated Universal Time), previously known as Greenwich Mean Time (GMT).
When you ask the OS for a Date object converted from "2017-03-14" you get a date/time reference of Midnight the morning of 2017-03-14 in your time zone which is, correctly, 10:00 pm (22:00) then night before in UTC.
When you ask the OS for a Date object for now with Date() you get a date/time reference of now in your time zone, which will be two hours earlier in UTC.
To accurately evaluate your date string to say "is now earlier than 'tonight of 2017-03-14'" you will probably want to convert from "2017-03-14 23:59" (or 11:59 pm, or perhaps prior to the start of tonight's event of 8:00 pm, etc).
This will do your original comparison, but would work better as a function (although I'm not sure how you want to use it)...
var newDateString : String = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
// set tonightDate to 1 minute before midnight, tonight, in local time
if let tonightDate = dateFormatter.date(from: "2017-03-14 23:59") {
// set nowDate to current local time
let nowDate = Date()
let comp = nowDate.compare(tonightDate)
if comp.rawValue <= 0 {
newDateString = "TONIGHT"
} else {
dateFormatter.dateFormat = "EEEE, MMMM d, yyyy"
newDateString = dateFormatter.string(from: tonightDate)
}
}
print(newDateString)
It is calculated time based on UTC so you are getting day before.You can get proper format using below code:
func chageDateFormat(date:String) -> String{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let date = dateFormatter.dateFromString(date) else {
assert(false, "No date from string")
return ""
}
print(date)
dateFormatter.dateFormat = "EEEE, dd MMMM, yyyy"
let result = dateFormatter.stringFromDate(date)
return result
}
let resultFormateDate = chageDateFormat("2017-03-14")
For comparison you also need to convert Date() to proper format.Both date must be in same format.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = NSDate()
let strdate = dateFormatter.stringFromDate(date)
let resultFormateDate2 = chageDateFormat(strdate)
Now you can compare two strings
if resultFormateDate == resultFormateDate2{
print("True")
}

Convert string to date in Swift

How can I convert this string "2016-04-14T10:44:00+0000" into an NSDate and keep only the year, month, day, hour?
The T in the middle of it really throws off what I am used to when working with dates.
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!
Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
Finally create a new Date object and strip minutes and seconds
let finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 10.12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
Try the following Date Format.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter.dateFromString(strDate)
For Swift 4.1:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter.date(from: strDate)
In Swift 4.1 you can do:
func getDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale.current
return dateFormatter.date(from: "2015-04-01T11:42:00") // replace Date String
}
Swift 3.0 - 4.2
import Foundation
extension String {
func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
dateFormatter.locale = Locale(identifier: "fa-IR")
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: self)
return date
}
}
extension Date {
func toString(withFormat format: String = "EEEE ، d MMMM yyyy") -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "fa-IR")
dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
dateFormatter.calendar = Calendar(identifier: .persian)
dateFormatter.dateFormat = format
let str = dateFormatter.string(from: self)
return str
}
}
make global function
func convertDateFormat(inputDate: String) -> String {
let olDateFormatter = DateFormatter()
olDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let oldDate = olDateFormatter.date(from: inputDate)
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "MMM dd yyyy h:mm a"
return convertDateFormatter.string(from: oldDate!)
}
Called function and pass value in it
get_OutputStr = convertDateFormat(inputDate: "2019-03-30T05:30:00+0000")
and here is output
Feb 25 2020 4:51 PM
Swift 5. To see IF A DATE HAS PASSED:
let expiryDate = "2020-01-10" // Jan 10 2020
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if Date() < dateFormatter.date(from: expiryDate) ?? Date() {
print("Not Yet expiryDate")
} else {
print("expiryDate has passed")
}
Converting string to Date in swift using the string extension
Swift - 5.0
extension String {
public enum DateFormatType {
/// The ISO8601 formatted year "yyyy" i.e. 1997
case isoYear
/// The ISO8601 formatted year and month "yyyy-MM" i.e. 1997-07
case isoYearMonth
/// The ISO8601 formatted date "yyyy-MM-dd" i.e. 1997-07-16
case isoDate
/// The ISO8601 formatted date and time "yyyy-MM-dd'T'HH:mmZ" i.e. 1997-07-16T19:20+01:00
case isoDateTime
/// The ISO8601 formatted date, time and sec "yyyy-MM-dd'T'HH:mm:ssZ" i.e. 1997-07-16T19:20:30+01:00
case isoDateTimeSec
/// The ISO8601 formatted date, time and millisec "yyyy-MM-dd'T'HH:mm:ss.SSSZ" i.e. 1997-07-16T19:20:30.45+01:00
case isoDateTimeMilliSec
/// The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/"
case dotNet
/// The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200"
case rss
/// The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200"
case altRSS
/// The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT"
case httpHeader
/// A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy"
case standard
/// A custom date format string
case custom(String)
/// The local formatted date and time "yyyy-MM-dd HH:mm:ss" i.e. 1997-07-16 19:20:00
case localDateTimeSec
/// The local formatted date "yyyy-MM-dd" i.e. 1997-07-16
case localDate
/// The local formatted time "hh:mm a" i.e. 07:20 am
case localTimeWithNoon
/// The local formatted date and time "yyyyMMddHHmmss" i.e. 19970716192000
case localPhotoSave
case birthDateFormatOne
case birthDateFormatTwo
///
case messageRTetriveFormat
///
case emailTimePreview
var stringFormat:String {
switch self {
//handle iso Time
case .birthDateFormatOne: return "dd/MM/YYYY"
case .birthDateFormatTwo: return "dd-MM-YYYY"
case .isoYear: return "yyyy"
case .isoYearMonth: return "yyyy-MM"
case .isoDate: return "yyyy-MM-dd"
case .isoDateTime: return "yyyy-MM-dd'T'HH:mmZ"
case .isoDateTimeSec: return "yyyy-MM-dd'T'HH:mm:ssZ"
case .isoDateTimeMilliSec: return "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
case .dotNet: return "/Date(%d%f)/"
case .rss: return "EEE, d MMM yyyy HH:mm:ss ZZZ"
case .altRSS: return "d MMM yyyy HH:mm:ss ZZZ"
case .httpHeader: return "EEE, dd MM yyyy HH:mm:ss ZZZ"
case .standard: return "EEE MMM dd HH:mm:ss Z yyyy"
case .custom(let customFormat): return customFormat
//handle local Time
case .localDateTimeSec: return "yyyy-MM-dd HH:mm:ss"
case .localTimeWithNoon: return "hh:mm a"
case .localDate: return "yyyy-MM-dd"
case .localPhotoSave: return "yyyyMMddHHmmss"
case .messageRTetriveFormat: return "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
case .emailTimePreview: return "dd MMM yyyy, h:mm a"
}
}
}
func toDate(_ format: DateFormatType = .isoDate) -> Date?{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format.stringFormat
let date = dateFormatter.date(from: self)
return date
}
}
we use like
string.toDate(.isoDate)
"1997-05-24".toDate(.isoDate)
Hi You have separate T Format and then convert as you like
// create dateFormatter with UTC time format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-04-01T11:42:00")
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let timeStamp = dateFormatter.stringFromDate(date!)
Since iOS 15.0, we can convert a String to Date in a more swift way:
let strategy = Date.ParseStrategy(format: "\(year: .defaultDigits)-\(month: .twoDigits)-\(day: .twoDigits)T\(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits):\(second: .twoDigits)\(timeZone: .iso8601(.short))", timeZone: .current)
let date = try? Date("2016-04-14T10:44:00+0000", strategy: strategy)
Just your passing your dateformate and your date then you get Year,month,day,hour. Extra info
func GetOnlyDateMonthYearFromFullDate(currentDateFormate:NSString , conVertFormate:NSString , convertDate:NSString ) -> NSString
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = currentDateFormate as String
let formatter = NSDateFormatter()
formatter.dateFormat = Key_DATE_FORMATE as String
let finalDate = formatter.dateFromString(convertDate as String)
formatter.dateFormat = conVertFormate as String
let dateString = formatter.stringFromDate(finalDate!)
return dateString
}
Get Year
let Year = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "YYYY", convertDate: "2016-04-14T10:44:00+0000") as String
Get Month
let month = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "MM", convertDate: "2016-04-14T10:44:00+0000") as String
Get Day
let day = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "dd", convertDate: "2016-04-14T10:44:00+0000") as String
Get Hour
let hour = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "hh", convertDate: "2016-04-14T10:44:00+0000") as String
I was getting crazy with this format as well.
See the solution below.
Your String that came from your back or another source:
let isoDate = "2020-05-06 20:00:00-03"
Identify the date format
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!
Now that you have the date as Date() you can change to whatever format you want using the formatDate.string
let formatDate = DateFormatter()
formatDate.dateFormat = "dd/MM/yyyy HH:mm"
let drawDate = formatDate.string(from: date)
print(drawDate)
Output:
06/05/2020 20:00
just
Step 1 >
get the String value from JSON or dataSource
Step 2 > create a local variable and assign it.
let startDate = CurrentDashBoard.startdate
Step 3> create an instance of DateFormatter.
let dateFormatter = DateFormatter()
step 4>
call the dateFormat from dateFormatter and provide saved date dataType.
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"("may be String formate")
step 5>
Assign the Local variable to this variable to convert.
let dateFromStringstartDate : NSDate = dateFormatter.date(from: startDate)! as NSDate
Step 6>
provide your required date Formate by the following code.
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
Step 6> Assign it to label/text
cell.lblStartDate.text = String(format: "%#", strstartDate)
Code:
let startDate = CurrentDashBoard.startdate let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss" let dateFromStringstartDate :
NSDate = dateFormatter.date(from: startDate)! as NSDate
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let strstartDate = dateFormatter.string(from: dateFromStringstartDate as Date)
Sometimes, converting string to Date in swift can result to return nil so that you should add "!" mark to format.date function!
let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"
let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!
In swift4,
var Msg_Date_ = "2019-03-30T05:30:00+0000"
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd yyyy h:mm a" //"MMM d, h:mm a" for Sep 12, 2:11 PM
let datee = dateFormatterGet.date(from: Msg_Date_)
Msg_Date_ = dateFormatterPrint.string(from: datee ?? Date())
print(Msg_Date_)
//output :- Mar 30 2019 05:30 PM
Swift 5.6
Here is an easy way to get a string and convert it back to string with Date in structure by String extension
Date String Example "2022-03-15T07:13:49.607+00:00"
If the date is not in the format "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ"
It will return 01-01-70
import Foundation
extension String {
func convertToDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ"
if let dt = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "MM-dd-yy"
let formatedStringDate = dateFormatter.string(from: dt)
return formatedStringDate
}
return "01-01-70"
}
}
Just use SwifterSwift.
stringDate = "2020-04-26T08:56:17.987Z"
let date = Date(iso8601String: stringDate)
What about SwiftDate ?. The best Date and Time parsing and manipulation library for Swift.
https://github.com/malcommac/SwiftDate#1-date-parsing
Install using Cocoa Pods:
https://github.com/malcommac/SwiftDate/blob/master/Documentation/0.Informations.md#installation
And then:
import SwiftDate
// All default datetime formats (15+) are recognized automatically
let _ = "2010-05-20 15:30:00".toDate()
// You can also provide your own format!
let _ = "2010-05-20 15:30".toDate("yyyy-MM-dd HH:mm")
// All ISO8601 variants are supported too with timezone parsing!
let _ = "2017-09-17T11:59:29+02:00".toISODate()
// RSS, Extended, HTTP, SQL, .NET and all the major variants are supported!
let _ = "19 Nov 2015 22:20:40 +0100".toRSS(alt: true)
Please use an ISO8601 parsing library for doing this. There are too many ways how the string could be encoded. Don't rely on a specific format and don't rely on the server sending always the same. The problems start with the 'Z' at the end and it will extend through all varieties of the standard. A parsing library will handle all cases and will always provide a safe conversion - whereas a fixed formatting string is likely to fail in the future.
You could use one of these libraries. They are also available on CococaPods:
https://github.com/boredzo/iso-8601-date-formatter/
https://github.com/malcommac/SwiftDate
Take a look at the implementations. They are both several hundred lines long - for good reason.
With regards to the question: You can pull out the date components from the date using NSDateComponents. The example on the website covers exactly your case.
https://developer.apple.com/documentation/foundation/nscalendar/1414841-components?language=objc
Please be aware, that converting your date will take into account the time zone. You might want to set the 'locale' of the NSCalendar explicitly.