Swift D-Day UIPickerDate - swift

I have a
#IBOutlet weak var EndDatePicker: UIDatePicker?
what I want to is, If a string called date is nil, set the datePicker to Today, the "D-Day":
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if(task?.date != nil){
let date = dateFormatter.dateFromString(task!.date!)
EndDatePicker!.date = date!
}else{
//EndDatePicker!.date = D-Day?
}
Thank you for your help, I don't find on internet the way to do this on swift.
Regards.

try this :
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = dateFormatter.stringFromDate(NSDate())
let text = dateString

Since Swift 1.2 you can perform two optional binding checks in the same line.
The first check is if date is nil, the second if the dateformatter could create a valid date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let dateString = task?.date, date = dateFormatter.dateFromString(dateString) {
EndDatePicker.date = date
}
else {
EndDatePicker.date = NSDate()
}

Related

SwiftUI string to formatted date (ISO)

can you please help me with that topic?
from the API i get the following date as a string: 2021-05-21T14:35:15.647+02:00
How can i convert this to a date object, so that i can format it?
I tried it in different ways as subscribed here in stackoverflow or in other tutorials, like this:
let date = "2021-05-21T14:35:15.647+02:00"
func formatStringDate(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let newDate = dateFormatter.date(from: date)
dateFormatter.setLocalizedDateFormatFromTemplate("MMMM d, yyyy")
return dateFormatter.string(from: newDate!)
}
var newDate = formatStringDate(date: date)
print(newDate)
or
let timestampString = "2018-12-09T11:08:48-05:00"
if let date = isoDateFormatter.date(from: timestampString) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM, dd, yyyy h:mm a"
let dateFormattedString = dateFormatter.string(from: date)
print(dateFormattedString) // December, 09, 2018 11:08 AM
} else {
print("not a valid date")
}
But it´s not working.
Thanks for your help
Thanks for your help, i got the following snippet to work:
let dateString = "2021-05-21T14:35:15.647+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate
]
let date = inputFormatter.date(from: dateString)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.YYYY"
print(dateFormatter.string(from: date!))
Thanks

Parsing a Swift String to Date, then Components

I have a date "2017-12-31" as a String.
What I want to get finally is only the month: "12" as a String.
So I thought that I can change it to Date using a date formatter
let formatter = DateFormatter()
formatter.dateFormat = "MM"
What do I do next?
let dateString = "2017-12-31"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601) formatter.timeZone = TimeZone(identifier: TimeZone.autoupdatingCurrent.identifier)
formatter.dateFormat = "yyyy-MM-dd"
let localDate = formatter.date(from: dateString)
formatter.dateFormat = "MM"
let strMonth = formatter.string(from: localDate!)
print("Month is:",strMonth)
Another way
let dateString = "2017-12-31"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let localDate = formatter.date(from: dateString)
let month = String(NSCalendar.current.component(.month, from: localDate!))
print(month)
First you have to use the DateFormatter to create a temporary Date object from your source String object. Then you have to use it to create your final String from the temporary Date object.
let dateString = "2017-12-31"
let dateFormatter = DateFormatter()
// set the dateFormatter's dateFormat to the dateString's format
dateFormatter.dateFormat = "yyyy-MM-dd"
// create date object
guard let tempDate = dateFormatter.date(from: dateString) else {
fatalError("wrong dateFormat")
}
// set the dateFormatter's dateFormat to the output format you wish to receive
dateFormatter.dateFormat = "LL" // LL is the stand-alone month
let month = dateFormatter.string(from: tempDate)
Use below function for getting month from string file of date
func getMonthFromDateString(strDate: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: strDate) // Convert String File To Date
formatter.dateFormat = "MM"
let strMM = formatter.string(from: date!) // Convert date to string
return strMM
}

Date formatter crash in swift

Please help me to modify this part of code,
if let dateVaule = UserDefaults().value(forKey: SplashSeenDate){
let dateStr = dateVaule as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone.ReferenceType.local
let date = dateFormatter.date(from:dateStr)
if Global.sharedInstance.Splashs != nil && Global.sharedInstance.Splashs?.count != 0{
for (i,splash) in (Global.sharedInstance.Splashs?.enumerated().reversed())!{
if !checkTimeStamp(date: splash.create_timestamp,StoredDate: date!){
Global.sharedInstance.Splashs?.remove(at: i)
}
}
print(Global.sharedInstance.Splashs?.count ?? "-1")
}
}
Honestly speaking, i am very confuse with the date formatter.
when this project launch, it occured crash at
if !checkTimeStamp(date: splash.create_timestamp,StoredDate: date!){
However, I could not replicate this crash... **Only a few user with iOS10 occured this crash.**Please kindly advise, Thanks a lot!
func checkTimeStamp(date: String!,StoredDate: Date) -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier:"en_US_POSIX")
let datecomponents = dateFormatter.date(from: date)
if (datecomponents! >= StoredDate) {
return true
} else {
return false
}
}
You are converting String to Date in two different ways:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone.ReferenceType.local //###Why don't you use `TimeZone.current`?
let date = dateFormatter.date(from:dateStr)
And in checkTimeStamp(date: String!,StoredDate: Date) -> Bool:
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier:"en_US_POSIX")
let datecomponents = dateFormatter.date(from: date)
In your case, lacking this line is critical for your first conversion:
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
You can find many articles discussing about DateFormatter (or NSDateFormatter in old articles) returning nil.
When you use DateFormatter with fixed format like "yyyy-MM-dd HH:mm:ss", you must set locale to Locale(identifier: "en_US_POSIX").
Maybe you'd better define one conversion method (or computed property) to convert String to Date which fits for your app's requirements, and use it everywhere you need String to Date conversion:
extension String {
var toAppDate: Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale(identifier: "en_US_POSIX") //### <- Do not miss.
return dateFormatter.date(from: self)
}
}
Generally, your code uses too much forced-unwrapping or forced-casting. You can re-write it without using any forced-something:
if
let dateStr = UserDefaults().string(forKey: SplashSeenDate),
let date = dateStr.toAppDate,
let splashes = Global.sharedInstance.Splashs, !splashes.isEmpty
{
//### In most cases, `filter` is faster than repeated `remove`.
Global.sharedInstance.Splashs = splashes.filter {
checkTimeStamp(date: $0.create_timestamp, storedDate: date)
}
print(Global.sharedInstance.Splashs?.count ?? "-1")
}
(Assuming create_timestamp is not Optional, and renamed parameter label StoredDate: to storedDate:.)
Seems like splash.create_timestamp is getting nil and when you are passing in this function checkTimeStamp. It is getting crash. You can prevent the crash by changing date parameter inside checkTimeStamp function as optional and use guard statement before passing inside the function.

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.

NSDateFormatter dateFromString returns nil for "2015-11-20 13:42:00.000000"

I know there are many similar questions but I can't figure out my problem.
I want to convert a String like "2015-11-20 13:42:00.000000" to NSDate.
My code is like below.
let date:String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
if let value = row["date"]?.asString() {
date = value
let formattedDate = dateFormatter.dateFromString(date) // formattedDate is nil
}
You need to update your dateFormat with following
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
As uppercase S represents fraction of second.
More detail about DateTime Format table is available here
Please secure your code by saving ponies !
let date = "2015-11-20 13:42:00.000000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
if let fornmattedDate = dateFormatter.dateFromString(date) as NSDate {
print ("The formated date is \(fornmattedDate)")
} else {
print ("\(date) is not a valid date")
}
Try like this :-
let date = "2015-11-20 13:42:00.000000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
let fornmattedDate = dateFormatter.dateFromString(date) as NSDate!
print ("The formated date is \(fornmattedDate)")
Output:-
The formated date is 2015-11-20 21:42:00 +0000