Cannot find the right logic to translate the NSDate to string - swift

I am very new to swift and found this one difficult, so its saying that it cannot be parsed to a variable because its not a string.
I searched and found something but it was not related near to my type of code so I am kindly asking for it :)
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.date(from: currentVechicle.LastCommunicationDate!) as NSDate?
print(dateFormatterPrint.string(from: date! as Date))
cell.perditsuarOutlet.text = date // Error: Cannot assign value of type 'NSDate?' to type 'String?'

You are printing the correct String value, but assigning the variable date which typed as NSDate? to the text property, which should be a String.
Try doing this:
let dateString = dateFormatterPrint.string(from: date! as Date)
cell.perditsuarOutlet.text = dateString
One piece of advice: don't force unwrap here (date! as Date). Instead, include a way to handle nil values for your "optional" NSDate? variable. One way to do this would look like this:
if let date = dateFormatterGet.date(from: currentVechicle.LastCommunicationDate!) as NSDate? {
cell.perditsuarOutlet.text = dateFormatterPrint.string(from: date as Date)
} else {
cell.perditsuarOutlet.text = "Empty or invalid date"
}
I know this looks like a lot of overhead, but it is worth it to avoid crashes down the line...

your date constant is an NSDate.
and the cells text property is a String.
You can't pair the two together since they aren't the same type.
Since you can't change the cells text type, that only leaves you with 1 option. You'll have to turn the NSDate into a String.
I recommend taking a look at Paul Hudsons 100 Days of Swift. It was a fantastic resource when I first started. The link I've provided points to his lessons from Day 1 about Strings
Keep up the good work. I promise it gets better :)

Related

I'm trying to enter a formatted date string as "yyyy-mm-dd H:i:s +0000" mySQL from Swift 5. Instead, I get "yyyy-mm-dd H:i:s 0000". How to add "+"?

#objc func datePickerDidChange(_ datePicker: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
birthdayTextField.text = formatter.string(from: datePicker.date)
let compareDateFormatter = DateFormatter()
compareDateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
let compareDate = compareDateFormatter.date(from: "2013/01/01 00:01")
if datePicker.date < compareDate! {
birthdayContinueButton.isHidden = false
} else {
birthdayContinueButton.isHidden = true
}
}
You ask:
I get “yyyy-mm-dd H:i:s 0000”. How to add “+”?
Your date string in your code snippet is “2013/01/01 00:01”. There is neither “+0000” nor “0000” (nor seconds) there. So there is no + to add or remove.
FWIW, if you print a Date object, yes, it will print a date in the format of 2013-01-01 00:01:00 +0000. But that’s immaterial. That’s just how print will display Date on your console. But you do not care what debugging format print uses. All you care about is whether the DateFormatter correctly parsed the date (and how a separate DateFormatter will prepare the date string for display in the UI).
Bottom line, do no worry about how print displays Date objects. (If anything, the fact that it is including the timezone for debugging purposes is very useful.) Just make sure your date formatters are correctly parsing/generating date strings. And, when you want to display a date string in your UI, use a separate DateFormatter for that (but for that formatter, do not use dateFormat, but rather use dateStyle and timeStyle). For more information, compare the ”Working With User-Visible Representations of Dates and Times” and “Working With Fixed Format Date Representations” discussions in the DateFormatter documentation.

Swift convert Unix timestamp to Date with timezone and save it to EKEvent

I trying to convert my unix timestamp(Int) to the Date type in my app. I found a solution which is
let str = timeValue as? NSNumber
return Date(timeIntervalSince1970: str.doubleValue)
This solution works but how can I set the timezone. I found another solution that used the formatter but the formatter return string.
func convertDateTime(timeValue: Int) -> String {
let truncatedTime = Int(timeValue)
let date = Date(timeIntervalSince1970: TimeInterval(truncatedTime))
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "GMT+8")
formatter.dateFormat = "dd/MM/yyyy hh:mm a"
return formatter.string(from: date)
}
Anyone can answer me how to do so?
Edited: I want to save it as EKEvent.
Dates represent instants/points in time - "x seconds since a reference point". They are not "x seconds since a reference point at a location", so the timezone is not part of them. It makes no sense to "set the timezone of a Date", the same way it makes no sense to "set the number of decimal places of a Double".
It seems like you actually want to store a EKCalendarEvent. Well, EKCalendarEvents do have a timezone, because they are events that occur at a particular instant/day (occurrenceDate), in some timezone (timeZone). So you just need to set the timeZone property of the EKEvent, rather than the Date.

Date formatter from string swift [duplicate]

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'"

Converting string to date returns nil yyyMMdd

I am trying to convert my string to a date using a date formatter.
let timeSTR = "19740707"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd"
let date = dateFormatter.date(from:timeSTR)
i am getting nil in the date object. any other timeSTR for example "19740706" or "19740705" or any other option will work ...
we found that if we will add the following command
dateFormatter.timezone = Timezone(identifier:"UTC")
it's fix the problem ...
more similar date that will return nil are: 19560603 , 19440401, 19400601
any one have an idea what wrong with those values???
Adding Print screen from my Playground with value 19740707:
Adding Print screen from my Playground with value: "19740706"

can't convert time stamp date to string in swift 4

I'm trying to convert a timeStamp string date to Date.
The result always returns nil.
func getDatefromTimeStamp (str_date : String , strdateFormat: String) -> String {
// stringDate '2018-01-01T00:00:00.000+03:00'
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone!
let date = dateFormatter.date(from: str_date)
dateFormatter.dateFormat = strdateFormat
let datestr = dateFormatter.string(from: date!)
return datestr
}
Your primary issue is that the format "yyyy-MM-dd'T'HH:mm:ssZ" does not match a string such as "2018-01-01T00:00:00.000+03:00". That string contains milliseconds but your format doesn't.
Update your format to "yyyy-MM-dd'T'HH:mm:ss.SSSZ".
That will fix the nil result.
Then you should clean-up your use of NSTimeZone. Just use TimeZone.
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
But there is no need to set the timezone when parsing this string because the string includes timezone information.
However, you may or may not want a timezone set when converting the resulting Date into the new String. It depends on what result you want.
Do you want the final string in UTC time (which is what you will get with your current code) or do you want the final string in the user's local time?
If you want the final string in the user's local time, don't set the timezone property at all. It will default to local time.
First of i highly recommend that you use guards instead of forces
Secondly why are you setting the date format twice? the first time is dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" then a few lines later resetting it with the parameter you passed in dateFormatter.dateFormat = strdateFormat. pick one and set it in the beginning - that may be causing your problem
Thirdly if that above is not the problem - make sure that your date is exactly in the necessary format if it is at all wrong it will return nil. even spaces and colons have to be perfect, i suggest using string builder to make sure they are consistant