Date time conversion in swift 5 - ios

I want to convert 2021-04-23T07:43:52.532656+00:00 to 04 April, 2021 7:43 Am
I am getting the day month and year correct but I have problems when formatting the time can somebody help me
My problem when converting time - I want the same time but when formatting it goes to the current time zone
func dateFormating(date : String) -> Date{
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//yyyy-MM-dd'T'HH:mm:ssZ
// var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
// dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.date(from: date) ?? Date()
}
func dateConverter(date : Date) -> String {
print("date in here 1 = \(date)")
let dateFormatterNormal = DateFormatter()
dateFormatterNormal.dateFormat = date.dateFormatWithSuffix()
// var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
// dateFormatterNormal.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// dateFormatterNormal.locale = Locale(identifier: "en_US_POSIX")
// dateFormatterNormal.timeZone = TimeZone.current
let endDate = dateFormatterNormal.string(from: date )
print("endinf date == \(endDate)")
return endDate
}
func dateFormatWithSuffix() -> String {
return " MMM , yyyy h:mm a"
}

Related

How to convert string date time format to another format using Swift

In my scenario, I am trying to convert date time string one format to another format 26 Nov, 2019 - 2:53 AM to yyyy-MM-dd h:mm:ss. How to cover the format?
Below Code Returning Empty
let dateString = "26 Nov, 2019 - 2:53 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateres = dateFormatter.date(from: dateString)
print(dateres)
extension String {
func convertToDateFormate(current: String, convertTo: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = current
guard let date = dateFormatter.date(from: self) else {
return self
}
dateFormatter.dateFormat = convertTo
return dateFormatter.string(from: date)
}
}
convert to required formate as
let dateString = "12-10-2019"
let convertedDate = dateString.convertToDateFormate(current: "dd-MM-YYYY", convertTo: "YYYY-MM-dd")
Try This
Step 1:- Put this function on your class file
func convertDate(date: String, dateFormat : String, convertFormat : String) -> String {
let datetimeFormatOriginal = DateFormatter()
datetimeFormatOriginal.dateFormat = dateFormat
let convertedFormat = DateFormatter()
convertedFormat.dateFormat = convertFormat
if date == "" || date == "-" {
return "-"
}
else {
return convertedFormat.string(from: datetimeFormatOriginal.date(from: date)!)
}
}
Step:- 2 Now using this function convert date
let convertedDate = convertDate(date: "26 Nov, 2019 - 2:53 AM", dateFormat: "dd MMM, yyyy - HH:mm aa", convertFormat: "yyyy-MM-dd hh:mm a")
print(convertedDate)
OUTPUT
"2019-11-26 12:53 AM"

How to change string datetime format to another format using Swift

I am trying to change date time concatenation and changing string input format to another format. I tried below code. Here, I can able to change the date format but need to concatenate current time before passing input date string.
My Code Below
override func viewDidLoad() {
super.viewDidLoad()
let result = formattedDateFromString(dateString: "28 Aug, 2019", withFormat: "dd-MM-yyyy")
self.resultLabel.text = result
}
func formattedDateFromString(dateString: String, withFormat format: String) -> String? {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "dd/MM/yyyy"
if let date = inputFormatter.date(from: dateString) {
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = format
return outputFormatter.string(from: date)
}
return nil
}
Expected output like :
28-08-2019 5:00 PM
func formattedDateFromString(dateString: String, withFormat format: String) -> String? {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "dd MMM, yyyy"
if let date = inputFormatter.date(from: dateString) {
print(date)
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = format
return outputFormatter.string(from: date)
} else {
print("nope")
}
return nil
}
let result = formattedDateFromString(dateString: "28 Aug, 2019", withFormat: "dd-MM-yyyy - h:mm a")
print(result)
Outputs:
"28-08-2019 - 12:00 AM"
In general I found this website to be really useful when trying to reason about dates in Swift/Objective-C
You can use this function
func convDate(dateToConvert: String) -> String? {
//Input Format
let df = DateFormatter()
df.dateFormat = "dd LL, YYYY"
//Convert input date string to date
guard let date = df.date(from: dateToConvert) else { print("Incorrect date format"); return nil }
//Output format
let outDF = DateFormatter()
outDF.dateFormat = "dd-MM-YYYY"
let hourDF = DateFormatter()
hourDF.dateFormat = "h:mm a"
hourDF.amSymbol = "AM"
hourDF.pmSymbol = "PM"
//format to string dd-MM-YYYY H:mm a
return outDF.string(from: date) + " " + hourDF.string(from: Date())
}
example
print(convDate(dateToConvert: "13 Aug, 2019"))

Convert string of format "19-07-2018 08:10:24" in date and time both different string format

I want to Convert string of format "19-07-2018 08:10:24" in date time format. If the date is today then it should be "02:12 am". If the date is of yesterday then it should be like "Yesterday". Otherwise it should be in "DD/MM/yy" format. Currently I am having the time and date in string formate.
I want the final answer in string type. If the answer is "DD/MM/YY", then it should be in string format.
Use the Calendar date functions:
func format(date: Date) -> String {
let calendar = Calendar.current
if calendar.isDateInToday(date) {
// process your "Today" format
return ...
}
if calendar.isDateInYesterday(date) {
// process your "Yesterday" format
return ...
}
if calendar.isDateInTomorrow(date) {
// process your "Tomorrow" format
return ...
}
// process your "full date/time format"
return ...
}
You can read more about the Calendar functions here: https://developer.apple.com/documentation/foundation/calendar
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"//19-07-2018 08:10:24
let date = dateFormatter.date(from: "15-07-2018 08:10:24")
dateFormatter.dateFormat = "dd/MM/yyyy"
let startDate = dateFormatter.string(from: date!)
let dateToday = (Calendar.current as NSCalendar).date(byAdding: .day, value: 0, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateToday = dateFormatter.string(from: dateToday1)
let dateYesterday = (Calendar.current as NSCalendar).date(byAdding: .day, value: -1, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateYesterday = dateFormatter.string(from: dateYesterday1)
if(startDate == strdateToday)
{
dateFormatter.dateFormat = "HH:mm"
let startDate = dateFormatter.string(from: date!)
print(startDate)
}
else if(startDate == strdateYesterday)
{
print("Yesterday")
}
else
{
print(startDate)
}

Convert string to DATE type in swift 3 [duplicate]

This question already has answers here:
Dateformatter to get Date From String
(4 answers)
Closed 4 years ago.
I have this structure:
struct message {
var id: String = "0"
var text: String = ""
var date: Date!
var status: String = ""
}
I have to load this structure from dbase, that it export in String format also date.
So I write this code to convert String to Date type:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
let dataDate = dateFormatter.date(from: elemMessage["date"] as! String)!
And I load it in structure:
message(id: elemMessage["id"] as! String, text: elemMessage["text"] as! String, date: dataDate as! Date, status: elemMessage["status"] as! String)
But I have this warning: "Cast from Date to unrelated type Date always fails"
So if I run app it will fails.
How Can I fix this, the date var in structure have to be Date type.
Thank you.
You can convert String Date into Date/NSDate like below code: -
Swift 3.2 & Swift 4.2
String to Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy" //Your date format
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
//according to date format your date string
guard let date = dateFormatter.date(from: "01-01-2017") else {
fatalError()
}
print(date) //Convert String to Date
Date to String
dateFormatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateFormatter.string(from: date) //pass Date here
print(newDate) //New formatted Date string
Output: -
2017-01-11 00:07:00 +0000
Jan 11, 2017
Swift 4 ISO
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
func getDateFromString(dateStr: String) -> (date: Date?,conversion: Bool)
{
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let dateComponentArray = dateStr.components(separatedBy: "/")
if dateComponentArray.count == 3 {
var components = DateComponents()
components.year = Int(dateComponentArray[2])
components.month = Int(dateComponentArray[1])
components.day = Int(dateComponentArray[0])
components.timeZone = TimeZone(abbreviation: "GMT+0:00")
guard let date = calendar.date(from: components) else {
return (nil , false)
}
return (date,true)
} else {
return (nil,false)
}
}
//Input: "23/02/2017"
//Output: (2017-02-23 18:30:00 +0000, true)

Date picker shows a different date (1 day behined) from when picked

I have a UIDatePicker that is connected to a UILabel. I want the user to pick a birthday that is more than 18 years ago (age restriction). So I have this line to set the maximumDate value:
datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -18, toDate: NSDate(), options: [])
This line however causes the picker to show a 1 day behind the selected date. for example if I choose September 27, 1956 on the picker the label shows September 26, 1956 I believe it has to do with NSDate() using a different timezone one that is behind my local timezone.
switch dequeueFrom[indexPath.row] {
case .Birthday:
if let pickedBday = pickedBday,
let bday = NSDate.dateFromISOString(pickedBday) {
(cell as! RegisterTextFieldCell).content(bday.longFormattedString())
}
// dateFromISOSString is declared in an extension.swift
class func dateFromComponents(components: NSDateComponents) -> NSDate? {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
class func dateFromString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-SSS"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
func ISOStringFromDate() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return dateFormatter.stringFromDate(self).stringByAppendingString("Z")
}
class func dateFromISOString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
Any help with how I can make NSDate() be my local timezone so this one day behind issue can go away? Any help is greatly appreciated :)
The problem is in your method ISOStringFromDate because you are getting the local time and manually adding the Z (Z means UTC) to the string. Try like this when creating your iso8601:
extension NSDate {
var iso8601: String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter.stringFromDate(self)
}
}
and your code should be:
pickedDate.iso8601 // to get your date iso8601 string

Resources