This question already has answers here:
Convert string to date in Swift
(18 answers)
Closed 1 year ago.
var str = "2021-05-23T06:35:47.409Z"
var formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy, h:mm:ss a"
let formattedtoDate = formatter.date(from: str)
let formattedtoString = formatter.string(from: formattedtoDate) //Error Cannot force unwrap value of non-optional type 'String'
cell.date_announce.text = formattedtoString
I'm trying to format sting to Date() and format Date to String in order to set value to date_announce label. Can anyone help me please?
If you break down what you are trying to do, there are actually 2 steps that require two different date formatters.
Convert an input date string (e.g. "2021-05-23T06:35:47.409Z") to a Date
Convert the Date to an output string in a different format.
Try this code instead:
var str = "2021-05-23T06:35:47.409Z"
//Set up a DateFormatter for input dates in "Internet" date format"
var inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
//Set up an output date formatter (in the local time zone)
var outputFormatter = DateFormatter()
outputFormatter.dateFormat = "MMM d yyyy, h:mm:ss a"
if let formattedtoDate = inputFormatter.date(from: str) {
let formattedtoString = outputFormatter.string(from: formattedtoDate)
print("'\(str)' = '\(formattedtoString)'")
} else {
print("Can't convert the string \(str) to a Date")
}
Edit:
(As Leo Dabus pointed out in a comment, you usually should not use a fixed dateFormat string in a DateFormatter that generates user-visible date strings. Better to use date and time styles and let the DateFormattter pick a specific format appropriate to the user's locale and language.)
Related
This question already has answers here:
iOS Swift 3 : Convert "yyyy-MM-dd'T'HH:mm:ssZ" format string to date object
(3 answers)
Closed 2 years ago.
I need convert this string 2020-03-18T00:00:00 in date like this 2020.03.18 00:00
When i try to convert like this my app just crash.
public extension String {
var dateValue: Date {
let formatter = DateFormatter()
formatter.timeZone = .none
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return formatter.date(from: self)!
}
}
Any ideas?
The issue is that this code is using a dateFormat string of yyyy-MM-dd HH:mm, but that’s not what the actual input string is. It is yyyy-MM-dd'T'HH:mm:ss. Thus the conversion to the Date object is failing, and the forced unwrapping will cause it to crash.
Instead, I would recommend one formatter to convert the ISO8601 format of 2020-03-18T00:00:00 into a Date object. And if you then want a string in the format of 2020.03.18 00:00, you would have a separate formatter for that.
In the absence of an explicit timezone in ISO8601 date strings, it’s assumed to be the local time zone. So do not specify the timeZone property at all. (The only time you’d generally specify it is if it was Zulu/GMT/UTC, i.e. TimeZone(secondsFromGMT: 0).)
E.g.
let iso8601Formatter = DateFormatter()
iso8601Formatter.locale = Locale(identifier: "en_US_POSIX")
iso8601Formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy.MM.dd HH:mm"
func convert(input: String) -> String? {
guard let date = iso8601Formatter.date(from: input) else { return nil }
return formatter.string(from: date)
}
let result = convert(input: "2020-03-18T00:00:00") // "2020.03.18 00:00"
Note, instantiation of formatters (and changing of dateFormat strings) is a notoriously computationally intensive process, which is why I made these formatters properties rather than local variables. Obviously name them whatever you want and put them wherever you want, but make sure you avoid repeatedly instantiating these formatters or changing of dateFormat strings.
Your date formatter needs to include the "T"
dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'"
I would like to format my dates to not have zeros in the beginning.
For example
04/03/20 -> swift should display as 4/3/20
I basically want to remove the zero that may be in front of the day, month, or year. The purpose of this is not for style purposes but for me to access data in a JSON. That's why it needs to be soo specific.
You can get by using Date & DateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yy" // change formate as per your requirement
let date = formatter.date(from: "04/03/20") //change "04/03/20" to your input string
formatter.dateFormat = "d/M/yy"
let dateString = formatter.string(from: date!)
print(dateString) // 4/3/20
let date = "04/03/20"
let parts = date.split(separator: "/")
var newDate = ""
for i in 0..<parts.count {
newDate = "\(newDate)\(i == 0 ? "" :"/")\(Int(parts[i])!)"
}
print(newDate) //Result - 4/3/20
I am removing the current time from the current time and trying to find the minute difference. But it says 10/09/2019 13:13 and there is an error in the extraction process (I want to print as 1313) .1313 I can perform the extraction process. How do I print this data the way I want? I want to print dateFormat = "HHmm". In timertext2New.text, dateFormat = "dd / MM / yyyy HH: mm" like this. But I want to save it in HHmm format.
save12 output: 05/09/2019 10:48 but I want it to be "1048" . To perform extraction.
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
timertext2New.text = formatter.string(from: datePicker.date)
let timehafıza2 = String(self.timertext2New.text!)
let df2 = DateFormatter()
df2.dateFormat = "HHmm"
var str2 = df2.string(from: Date())
str2 = timehafıza2
UserDefaults.standard.setValue(str2, forKey: "timertext2")
override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HHmm"
let hour = dateFormatter.string(from: date)
var save12 = UserDefaults.standard.integer(forKey: "timertext2")
var fark : Int = (Int(hour)! - Int(save12))
}
Your code is pretty confusing and cannot work
You convert a date from a date picker with format "dd/MM/yyyy HH:mm"
Then you create a string with format "HHmm" from the current date which will be destroyed immediately because
You overwrite this string with the dd/MM/yyyy HH:mm string and save it to UserDefaults
Later you read the value from UserDefaults as integer which returns 0 because the "dd/MM/yyyy HH:mm" format is not representable by an integer.
My suggestion is to save all dates as Date and perform the date math with the dedicated methods of Calendar
I am trying to convert my string to a date using a static date formatter. When I make the call to stringToDate() using the variables below, a nil value is returned.
I've checked previous posts about this issue where people are saying it's because of the dateformatter locale or timeZone. However, that doesn't seem to be the issue in this case.
Does anyone know what the issue could be in this case? My code is below:
import Foundation
class DateHelper {
private static let dateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss"
df.locale = Locale(identifier: "en_GB")
df.timeZone = TimeZone.current
return df
}()
static func stringToDate(str: String, with dateFormat: String) -> Date? {
dateFormatter.dateFormat = dateFormat
let date = dateFormatter.date(from: str)
return date
}
}
var myDate = Date()
var dateStr = "2019-02-19T17:10:08+0000"
print(DateHelper.stringToDate(str: dateStr, with: "MMM d yyyy")) // prints nil
Looks like your string is in ISO8601 format. Use the ISO8601DateFormatter to get date instance. You can use ISO8601DateFormatter.Options to parse varieties of ISO8601 formats. For your string,
For Swift 4.2.1
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: dateStr)
print(date!)
Should output
"2019-02-19 17:10:08 +0000\n"
Your date format doesn't match your input date. Try this code:
print(DateHelper.stringToDate(str: dateStr, with: "yyyy-MM-dd'T'HH:mm:ssZZZZZ"))
Hope this helps.
I am trying to convert fajerTime to NSDate. When I compile the project the dateValue is nil. Any idea how to fix this issue?
if prayerCommingFromAdan.id == 0 && prayerCommingFromAdan.ringToneId != 0{
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)
let fajerTime = "\(prayer0.time[0...1]):\(prayer0.time[3...4])" as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
print(dateValue)
var dateComparisionResult:NSComparisonResult = NSDate().compare(dateValue)
if dateComparisionResult == NSComparisonResult.OrderedDescending {
addNotificationAlarm(year, month: month, day: day, hour: prayer0.time[0...1], minutes: prayer0.time[3...4], soundId: prayerCommingFromAdan.ringToneId, notificationBody: "It is al fajr adan")
}
The problem seems be the format of fajerTime. It looks like fajerTime is a time string, e.g. 12:34, whereas the date formatter is configured to accept string containing a month, day and year, e.g. 24-07-2016.
You need to format fajerTime to include the year, month and day, as well as the time. Also configure the date formatter to accept the full date and time.
Assuming prayer0 is an array, you will also need to combine the elements into a string, using joinWithSeparator.
e.g.
let hours = prayer0.time[0...1].joinWithSeparator("")
let minutes = prayer0.time[3...4].joinWithSeparator("")
let fajerTime = "\(month)-\(day)-\(year) \(hours):\(minutes)"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy hh:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
Please follow example (Swift 3):
let dateStr = "2016-01-15 20:10:01 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let myDate = dateFormatter.date(from: dateStr)
Keep in mind:
Date format e.g. "yyyy-MM-dd HH:mm:ss Z" must match the date string pattern
In your case, your date string contains only time, yet, your date
formatter contains only date
When using dateFormatter.date() there is no need to cast it to Date as it returns a Date:
Helpful website for date formats:
http://nsdateformatter.com/