Time stamp from string issue? - swift

I have two string , date and time . date string has a date in format "MM-dd-yyyy" and time in format "hh:mm a" , I want to create a 10 digit timestamp from the same . I did the following but I am getting issue with this. Any help is appreciated.
let idate = (userInstance.userData?.Date!)! + "T" + (userInstance.userData?.Time!)! + "+0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let date = dateFormatter.date(from: idate)!
print(date)
let timestamp = Int(date.timeIntervalSince1970)
print(timestamp)

You cannot force a date containing AM/PM time to ISO 8601. ISO 8601 dates are always represented in 24-hour mode.
Besides your order of year, month and day is not ISO 8601 compliant.
Specify the appropriate date format MM-dd-yyyyhh:mm aZ
let datePart = "09-18-2018"
let timePart = "4:22 pm"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM-dd-yyyyhh:mm aZ"
let date = dateFormatter.date(from: datePart + timePart + "+0000")!
let timestamp = Int(date.timeIntervalSince1970)
print(timestamp)

You are crashing here:
let date = dateFormatter.date(from: idate)!
That's because you are claiming that idate is a string in this format:
"yyyy-MM-dd'T'HH:mm:ssZ"
But it isn't. When you convert from a string to a date, your format string must exactly match the format of the string.
Then you can supply a different format and convert the date to a new string.

Related

Unable to convert string to date, string contains dot with 6 character [duplicate]

This question already has answers here:
How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?
(13 answers)
Closed 1 year ago.
I stuck to convert string to date, my date string is
"2021-03-25T06:35:36.372245"
Unable to convert it into date formate. I used the code but unable to convert, i got nil.
My code is
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss.ZZZZZZ" ( also tried SSSSSS)
let dte = dateFormatter.date(from: dateTime)
but unable to parse it. Kindly help me out.
You forget '' arround T
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
Do this
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let dte = dateFormatter.date(from: dateTime)

How can I convert GMT date to system date format?

I have a Date : 2019-07-18 00:30:32 GMT+10:00.
I want to convert string to date but its gives wrong date.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"
dateFormatter.timeZone = NSTimeZone.local;
dateFormatter.locale = NSLocale.current;
let date = dateFormatter.date(from:isoDate)!
Its gives wrong date : "Jul 17, 2019 at 8:00 PM"
When working with fixed format dates, such as RFC 3339, you set the
dateFormat property to specify a format string. For most fixed
formats, you should also set the locale property to a POSIX locale
("en_US_POSIX"), and set the timeZone property to UTC.
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
Reference : Apple
I seen it shows correct date, It is based on your Time zone:
Check with :
https://www.epochconverter.com/

Swift Convert date string to Date

I got a date string from server side, which is Tue, 28 May 2019 13:24:06 +0000. I tried to do following:
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")
result is nil
How can I convert a string like this to a Date?
You need to set a specific dateFormat. And when doing so, set the date formatter's locale to en_US_POSIX.
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")
See the documentation for dateFormat for links that take you a full description of what all of the format specifiers mean.
Keep in mind that when converting a Date to a String for display to the user, then using date and time styles is the best solution. But for parsing a String into a Date, use dateFormat.

Date Formatter isn't showing correct day of the month when using format "DD"

I am trying to show today's date as March 26 but it is showing as "March 85" when I use this code.
let formatter = DateFormatter()
formatter.dateFormat = "MMMM DD"
let defaultTimeZoneStr = formatter.string(from: Date())
The problem is that you are using the wrong date format. D is for "day of year". The correct symbol for "day of month" is lowercased d Thats why you are getting 85instead of 26.
Another point you should consider is to set your locale fixed to "en_US_POSIX" if you don't want your date string to reflect the users settings and locale.
Note that you should use Swift native type Date instead of NSDate.
If your intent is to display it respecting the user locale and settings you should use date formatter dateStyle (short, medium, long or full) How do I get the current Date in short format in Swift
If you need a localized date format limited to
month and day only, you can use DateFormatter method dateFormat from template:
class func dateFormat(fromTemplate tmplate: String, options opts: Int, locale: Locale?) -> String?
let df = DateFormatter()
df.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMMMdd", options: 0, locale: .current)
df.string(from: Date()) // "March 27"

Convert any time to GMT +3 in Swift

I would like to convert any time, UTC,, GMT+2 .. etc , anything to be only GMT +3
I tried this code but no success
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.timeZone = TimeZone.current
let currentdate = formatter.string(from: date)
print("currentdate \(currentdate)")
let gmt = DateFormatter()
gmt.timeZone = TimeZone(secondsFromGMT: 3600*3)
gmt.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let gmtDate = gmt.date(from: currentdate)!
print("gmtDate -> \(gmtDate)")
I tried abbreviations for the time zone, same result the date comes out to be only GMT.
Any ideas?
Your code has a lot of issues. First, there is no reason to go from Date to String and back to Date. Second, if you are converting a String to a Date, and the String contains its own timezone information, then setting the formatter's timeZone is pointless. The timezone in the string will be used when calculating the associated Date. There are only two cases where setting a date formatter's timezone makes sense:
When parsing a date/time string that does not contain any timezone information. The formatter's timezone will then be used to interpret the string.
When converting a Date to a String. The formatter's timezone will be used when generating the resulting string from the date.
If you simply want to show any Date as a String in a specific timezone then all you need is:
let date = Date() // some date
print("Original Date (in GMT): \(date)")
// Setup a formatter with a date and time style
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 3600 * 3) // the desired timezone
formatter.dateStyle = .long
formatter.timeStyle = .medium
let string = formatter.string(from: date)
print("GMT+3 style result: \(string)")
// For comparison, set the formatter to a specific format
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let string2 = formatter.string(from: date)
print("GMT+3 format result: \(string2)")
Output (for the en_US locale):
Original Date (in GMT): 2017-10-28 20:53:59 +0000
GMT+3 style result: October 28, 2017 at 11:53:59 PM
GMT+3 format result: 2017-10-28 23:53:59 +0300
There is no need to convert any time. Simply create a String from a Date to get the desired output.
Note that, by default, a DateFormatter shows its result in local time. Set the formatter's timeZone if you want the result in some other specific timezone.
Also note that printing a Date object always shows the date in UTC time (+0000). Many people get confused by this and think they are getting the wrong date when they are not.
Swift 5
private func convertDate(string:String) -> String {
let dateFormatter = DateFormatter()
// format in which the date and time comes from the server
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
// set the time zone, the time is stored on the server
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3")
// convert to Date
let date = dateFormatter.date(from: string)
// now set our local time zone
dateFormatter.timeZone = TimeZone.current
// time format we need
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
// convert the Date obtained above into text format
let displayString = dateFormatter.string(from: date!)
// local time is ready)))
return displayString
}