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

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.

Related

Where the time coming from when converting date string without any time in to Date() in swift?

I'm using this extension to convert a string containing date to Date() object:
extension String {
func toDate() -> Date?{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/YYYY"
let date = dateFormatter.date(from: self)
return date
}
}
the result always containing a time in it. I'm curious where is the time coming from, why it is not all zero?
print("11/12/2021".toDate())
result is ->
2020-12-19 21:00:00 +0000
In the time that I run the code, it is showing 21:00:00, so why it is 21? I believe It is not related to my time because I run it at different times.
A Date object indicates an instant in time anywhere on the planet, independent of time zone.
A DateFormatter can convert a String to a Date (or a Date to a String, but ignore that for now). When it converts a String to a Date, it may make assumptions about the time of day if that is not included in the String. I believe it assumes that the time is midnight (00:00:00) in the date formatter's time zone. (And by the way, midnight is the starting point of a day, so midnight is zero hours/minutes/seconds into the day. Essentially midnight IS zeros for time.)
So when you call your String extension to convert "11/12/2021" to a Date, the extension creates a DateFormatter which defaults to the device time zone. It creates a Date assuming Midnight in the local time zone.
When you print that date, it gets displayed in GMT.
It looks like your format string has problems though. You're getting the wrong year and month. I think you must be using the wrong month or day string in your formatter. (I always have to look those up when I use them.)
Edit:
You likely want a format string of "MM-dd-yyyy"
(2-digit month, 2-digit day of month, and 4-digit year.)
Lower-case "m" or "mm" is minutes. Upper-case "Y" is for "week of year" based calendars, which you probably don't want.
Try this code:
func toDate() -> Date?{
let dateFormatter = DateFormatter()
let posixLocale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.locale = posixLocale
let date = dateFormatter.date(from: self)
return date
}
}
And to use it:
let dateString = "12/11/2021"
let date = dateString.toDate()
print(date)
if let date = date {
let convertedDateString = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium)
print(convertedDateString)
} else {
print("Can't convert \(dateString) to a date")
}
That displays "Dec 11, 2021 at 12:00:00 AM" in my US locale (US Date formatting.) Note that since I use the DateFormatter class method localizedString(from:dateStyle:timeStyle:) I see midnight as the displayed time (The time you get from a DateFormatter when you don't specify a time, but displayed in the local time zone.)
The answer is:
when we are converting a string to a Date Object the important part is the time zone that we are converting it to.
for example, if you convert your string date to a UTC time zone when you want to bring it back you have to set the time zone of the date to UTC.
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "UTC")
so this is the reason why when we are printing the Date() object it is deferred from our string date.
extension String {
func toDate() -> Date?{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: self)
return date
}
}
extension Date {
func toString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
return dateFormatter.string(from: self)
}
}
let stringDate = "01-12-2021"
let date = "01-12-2021".toDate()
let convertBack = date?.toString()
print("(\(stringDate)) -> (\(date!)) -> (\(convertBack!))")
and the result is:
(01-12-2021) -> (2021-01-11 21:01:00 +0000) -> (01-12-2021)
so at the end when we convert back the Date object it will be the same. because that 2 dateFormatter in the extensions are using the default time zone. and if you want to specify a specific time zone you have to declare it in converting from and to string together.

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.

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

Swift 4.1 couldn't not convert String to local Date, always return UTC Date

I want to transfer a date string to Date.
let a = DateFormatter()
a.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let datea = a.date(from: "2018-06-21 00:00:00") else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
print("ans", datea)
But it always print "ans 2018-06-20 16:00:00 +0000"
Why it could not print the original string date "2018-06-21 00:00:00"?
What wrong with my code ?
A Date is not a string. A Date is a moment in time. It has no clock. It has no time zones. It has no calendar. It is just an instant in time, independent of location or localization.
As a debugging convenience, a Date can be easily converted to a string in a pre-defined format using its .description (which is what print calls). As with all .description methods, you should never use this string for anything but debugging (or possibly logging). There is no promise about what format this string is in.
If you need some specific string representation, then you should use the DateFormatter:
print("ans", a.string(from: datea))
You need to provide timeZone to get the time according to that provided timeZone so to convert UTC time to local time your code should be look like that.
let a = DateFormatter()
a.dateFormat = "yyyy-MM-dd HH:mm:ss"
a.timeZone = TimeZone(abbreviation: "UTC")
let dt = a.date(from: "2018-06-21 00:00:00")
a.timeZone = TimeZone.current
a.dateFormat = "yyyy-MM-dd HH:mm:ss" //change the dateFormat according to your need
let dateString = a.string(from: dt!)
print("now the dateString is \(dateString)")
//printed result (now the dateString is 2018-06-21 05:30:00 )
As Rob Napier says in his answer, a Date object does not have a time zone. It represents a moment in time anywhere on the planet.
If you want to display a Date as a month, day, year, and time, you need to specify a particular time zone.
If you just print a date, like print(Date()), you get the default description property of the date object, which shows the date expressed in UTC. That's probably not what you want.
I defined an extension to Date that lets me see dates expressed in the user's current locale and time zone:
extension Date {
func localString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
}
func timeString(timeStyle: DateFormatter.Style = .medium) -> String {
return localString(dateStyle: .none, timeStyle: timeStyle)
}
}
If you add that extension to your project you can use it like this:
print(print("ans", datea.localString())
And you'll see your Date in the device's current time zone. It's very useful for debugging.

Using DateFormatter produces a result which is off by a day

Using DateFormatter produces a result that is off by a day (actually 12 hours). Using the following code consistently produces dates that show as the previous day. I've been getting this in a number of applications for a while but just finally got around to digging into it.
extension Date
{
func display() -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
print(dateFormatter.locale)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let txt = dateFormatter.string(from: self)
print(txt)
return txt
}
}
Other questions that were in this vein suggested changing the locale, thus the added code for that, but I checked the locale and the actual date. If I add 8 hours to the date, I get the correct display result, but adding less than that does nothing. Some dates are being retrieved from the birthday field in the Contacts app, which yields dates that have a time of day 00:00:00 UTC. It would seem that I need to convert the date to local time? The timezone on the device is set to the local timezone (Pacific). That wouldn't seem so bad, but dates retrieved from a date picker aren't in UTC time, they're in local time. I haven't been able to figure out how to tell which timezone the date is in since using the calendar class and trying to extract the .timezone component says that "NSCalendarUnitTimeZone cannot be gotten by this method". Any suggestions on how to create a universal date formatter that works in all cases?
A couple of observations:
If your Date object is in UTC time zone, then set your formatter’s timeZone to TimeZone(secondsFromGMT: 0), too.
If you’re showing the string representation of a Date object in the UI, you do not want to use a locale of en_US_POSIX. You want to show it in the default locate of the device (i.e., don’t change the formatter’s locale at all). You only use en_US_POSIX when dealing with ISO 8601 and RFC 3339 date strings that are used internally or, for example, for exchanging date strings with a web service).
Finally, I would not specify a dateFormat string because not all users expect dates in MMMM dd, yyyy format. For example, UK users expect it in d MMMM yyyy format. When presenting dates in the UI, specify a dateStyle instead. Or, if none of those styles work, go ahead and specify dateFormat, but set it using setLocalizedDateFormatFromTemplate(_:) rather than a fixed string.
Thus, for your purpose, you would do:
extension Date {
var dateString: String {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter.string(from: self)
}
}
Or, if you're calling this a lot, you may want to reuse the formatter:
extension Date {
private static let formatterForDateString: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
var dateString: String {
return Date.formatterForDateString.string(from: self)
}
}
Use the timeZone property, to get the exact date, as shown as below:
formatter.timeZone = TimeZone(secondsFromGMT: 0)
it will solve your purpose!