Convert From String To date with 12 hours time formatting - swift

Since yesterday I'm trying to solve this issue but I give up. Now I have string date "2018-10-30 01:00 PM" and when I'm trying to convert it to date the time format will change to 24 hours. I mean it will be like "2018-10-30 13:00:00 UTC".
Here is my code:
let dateFormatter5 = DateFormatter()
dateFormatter5.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter5.locale = Locale(identifier: "en_US_POSIX")
dateFormatter5.timeZone = NSTimeZone(abbreviation: "GMT+0:00")! as TimeZone
let now = dateFormatter5.date(from: "2018-10-30 01:00 pm")!
I need to convert this string with the same time format (12 hours).
Any idea?

If your original date string is UTC timezone:
let dateStr = "2018-10-30 01:00 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
if let now = dateFormatter.date(from: dateStr) {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'UTC'"
dateFormatter.string(from: now) // "2018-10-30 13:00:00 UTC"
}

Related

Date Formatter unexpected output

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM dd, yyyy 'at' HH:mm:ss aa z"
dateFormatter.amSymbol = "AM"
let dateString = "February 02, 2022 at 10:49:06 AM GMT+3"
print(dateFormatter.date(from: dateString)!)
Prints -> 2022-02-01 21:49:06 +0000
why this prints 21:49 instead of 10:49?
So, yes, we're both missing something. The time format should be use hh not HH (HH is for 24 hour time and some weird conversation was going in there)
So, I tested in a Playground with...
let threeHoursFromGMT = Measurement(value: 3, unit: UnitDuration.hours).converted(to: UnitDuration.seconds).value
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm:ss aa z"
dateFormatter.amSymbol = "AM"
dateFormatter.timeZone = TimeZone.init(secondsFromGMT: Int(threeHoursFromGMT))
let dateString = "February 02, 2022 at 10:49:06 AM GMT+3"
let date = dateFormatter.date(from: dateString)!
dateFormatter.string(from: dateFormatter.date(from: dateString)!)
And it generated
"Feb 2, 2022 at 6:49 PM" // let date = dateFormatter.date(from: dateString)!
"February 02, 2022 at 10:49:06 AM GMT+3" // dateFormatter.string(from: dateFormatter.date(from: dateString)!)
The first output is based on my timezone (+11) and the second is based on the formatter requirements (using +3)

From UTC to local time doesn't consider daylight saving swift

I am using this function to convert UTC time to my local time stamp.
func UTCToLocal(date:String, timeZone: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone(identifier: timeZone)
dateFormatter.dateFormat = "h:mm a"
return dateFormatter.string(from: time)
}
But this doesn't check DST. So, I am getting one hour difference. Can anyone help me with some general solution for this problem?
Thanks to Leo who have figured out the issue. I have updated the functions as:
func UTCToLocal(date:String, timeZone: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone(identifier: timeZone)
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm aa"
return dateFormatter.string(from: dt!)
}
Now the date string in function paramter have value in this format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". This solves the issue.
The issue here is the lack of the date. You are always passing only the time components without the day so the daylight savings time Will always be correspondent to January 1st 2001. If you need today’s date you need to set the date formatter defaultDate property to the startOfDay for today. Btw don’t forget to set the locale first to “en_US_POSIX” before setting the fixed date format.

Convert UTC DateTime to local datetime does not show correctly in swift

I am using swift 4. I need to convert my UTC Time to local time.But it shows two hour before. I am now Living in dhaka with GMT+6. Here is code i used ..
var date:String = "2020-02-10 14:30:57 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss a"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
let convertedLocalTime = dateFormatter.string(from: dt!)
tv_time.text = convertedLocalTime
print("convertedLocalTime-->",convertedLocalTime)
It shows 2020-02-10 6:30 PM But now 8.30 PM . What is the wrong with the code
Please help me
Your input data is not correctly formatted.
If you can use a correct format for the input data:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
// set the date in UTC
let date = dateFormatter.date(from: "2020-02-10 14:30:57")
dateFormatter.timeZone = TimeZone.current
// String representation of the date for local time
let s = dateFormatter.string(from: date!)
this snippet sets s to "2020-02-10 15:30:57" which is correct for Germany.
Otherwise you have to correct the format of your input data, e.g. delete the "PM" from the 24h format string.

Convert time string to Unix time date of the same day

how to convert a string hour to millisecond of the day?
for exemple:
let strDate = "06:00 PM"
Or:
let strDate = "09:00 AM"
my code:
let dateString = "06:00 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
guard let date = dateFormatter.date(from: dateString)
else { fatalError() }
print(date)
for example my string is: 06:00 PM, so I want to have the date in millisecond of today Thursday 20 September 2018 at 06:00 PM
You can set your DateFormatter default date to startOfDay for today, set the formatter locale locale to "en_US_POSIX" when parsing your time then you can simply get your resulting date timeIntervalSince1970 and multiply by 1000:
let strTime = "06:00 PM"
let formatter = DateFormatter()
formatter.defaultDate = Calendar.current.startOfDay(for: Date())
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "hh:mm a"
if let date = formatter.date(from: strTime) {
let milliseconds = date.timeIntervalSince1970 * 1000
print(milliseconds) // 1537477200000
let date2 = Date(timeIntervalSince1970: milliseconds/1000)
print(date2.description(with: .current)) // Thursday, September 20, 2018 at 6:00:00 PM Brasilia Standard Time
}
First, you need to parse the date string:
let dateString = "06:00 PM"
let formatter = DateFormatter()
formatter.defaultDate = Date()
formatter.dateFormat = "hh:mm a"
formatter.locale = Locale(identifier: "en_US_POSIX")
let date = formatter.date(from: dateString)
Then, you need to get the start of day:
let calendar = Calendar.current
let start = calendar.startOfDay(for: date)
After that, get the time interval between date and start:
let timeInterval = date.timeIntervalSince(start)
let milliseconds = timeInterval * 1000.0

Get NSDate and convert it from the 24 hour format to 12 hour format in swift

I've seen this post for other languages but not for swift. I have a date saved in the format of 2015-08-31 21:36:00 +0000 and I'm able to extract the day, month, year and weekday with the code below to produce Monday, August 31, 2015. When I try to use:
let hourInt = components.hour
var hourString = String(hourInt)
It prints a four hour difference. In this case "17" for the "21". How do I
display it as 9:36 P.M.?
let flags: NSCalendarUnit = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
let date = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
let components = NSCalendar.currentCalendar().components(flags, fromDate: array.date)
let weekday = components.weekday
let weekdays = dateFormatter.weekdaySymbols
let weekdayString = weekdays[weekday-1] as! String
let month = components.month
let months = dateFormatter.monthSymbols
let monthString = months[month-1] as! String
let dayInt = components.day
var dayString = String(dayInt)
let year = components.year
let yearString = String(year)
println(weekdayString + ", " + monthString + " " + dayString + ", " + yearString)
Your date string suffix +0000 means it is UTC time if you want to display time at UTC you need to specify it when setting your date formatter.
let dateString = "2015-08-31 21:36:00 +0000"
let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = df.dateFromString(dateString) {
// now you have your date object
// to display UTC time you have to specify timeZOne UTC
df.timeZone = NSTimeZone(forSecondsFromGMT: 0)
df.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
let stringFromDate = df.stringFromDate(date)
println(stringFromDate) // "Monday, August 31, 2015 9:36:00 PM"
}
If you want to strip the time zone information, pass the GMT time zone.
This code does quite the same as yours
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
println(dateFormatter.stringFromDate(array.date))
Setting locale of NSDateFormatter to en_US_POSIX fixed issue for me.
let sharedFormatter:NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier:"en_US_POSIX")
return formatter
}()
sharedFormatter.dateFormat = "MMM d YYYY, h:mm a"
let dateString = sharedFormatter.stringFromDate(NSDate())
// Aug 2 2016, 5:45 PM
Swift 5.0
let dateString = "2015-08-31 21:36:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = dateFormatter.date(from: dateString) {
// now you have your date object
// to display UTC time you have to specify timeZOne UTC
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
let stringFromDate = dateFormatter.string(from: date)
print(stringFromDate) // "Monday, August 31, 2015 9:36:00 PM"
}