Swift 3.0 : Convert server UTC time to local time and vice-versa - swift

I want to convert server UTC time to local time and vice-versa.
Here is my code..
var isTimeFromServer = true
var time:String!
var period:String!
let timeString = "6:59 AM" //Current UTC time
if isTimeFromServer {
let index = timeString.index(timeString.startIndex, offsetBy: 5)
let twelve = timeString.substring(to: index)
var dateString:String!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm"
let date12 = dateFormatter.date(from: twelve)!
dateFormatter.dateFormat = "h:mm a"
let date22 = dateFormatter.string(from: date12)
//print(date22)
dateString = date22
//print("dateString=\(dateString)")
time = dateString.components(separatedBy: " ")[0]
period = dateString.components(separatedBy: " ")[1]
}
else {
time = timeString.components(separatedBy: " ")[0]
period = timeString.components(separatedBy: " ")[1]
}
var hour = Int(time.components(separatedBy: ":")[0])
hour = period == "AM" ? hour : hour! + 12
let minute = Int(time.components(separatedBy: ":")[1])
let calender = NSCalendar.current
var datecomponent = DateComponents()
datecomponent.calendar = calender
datecomponent.hour = hour
datecomponent.minute = minute
if !isTimeFromServer {
// local to UTC
datecomponent.timeZone = TimeZone.current
}
else {
datecomponent.timeZone = TimeZone(abbreviation: "UTC")
}
let date = datecomponent.date
let dateFormatter = DateFormatter()
if !isTimeFromServer {
dateFormatter.dateFormat = "H:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.string(from: date!)
}
else {
//UTC to local
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = TimeZone.current
dateFormatter.string(from: date!)
}
I get the local time
o/p: "12:52 PM"
But actual local time and output time difference is 23 minutes.

I don't know what's wrong with your code.But looks too much unnecessary things are there like you're setting calendar, fetching some elements from string.
Here is my small version of UTCToLocal and localToUTC function. But for that you need to pass string in specific format. Cause I've forcly unwrapped date objects. But you can use some guard conditions to prevent crashing your app.
func localToUTC(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.calendar = Calendar.current
dateFormatter.timeZone = TimeZone.current
if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "H:mm:ss"
return dateFormatter.string(from: date)
}
return nil
}
func utcToLocal(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "h:mm a"
return dateFormatter.string(from: date)
}
return nil
}
and call these function like below.
print(utcToLocal(dateStr: "13:07:00"))
print(localToUTC(dateStr: "06:40 PM"))

Mrugesh's answer is perfect, but if someone need to use their own formats, or in some different format, I've generalised it so you can give different format or same in both parameters.
func localToUTC(date:String, fromFormat: String, toFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = fromFormat
dateFormatter.calendar = NSCalendar.current
dateFormatter.timeZone = TimeZone.current
dateFormatter.date
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = toFormat
return dateFormatter.string(from: dt!)
}
func UTCToLocal(date:String, fromFormat: String, toFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = fromFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = toFormat
return dateFormatter.string(from: dt!)
}
let localDateAsString = UTCToLocal(date: dateAsString!, fromFormat: "hh:mm a, dd MMM yyyy", toFormat: "hh:mm a, dd MMM yyyy")
You can use it as above. Hope it helps.

By the help of Mrugesh Tank Answer,
I have updated his answer and creating the extensions for the date. So that you can easily access the functions from anywhere either from ViewController or either from cell class as well.
extension String {
//MARK:- Convert UTC To Local Date by passing date formats value
func UTCToLocal(incomingFormat: String, outGoingFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = incomingFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: self)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = outGoingFormat
return dateFormatter.string(from: dt ?? Date())
}
//MARK:- Convert Local To UTC Date by passing date formats value
func localToUTC(incomingFormat: String, outGoingFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = incomingFormat
dateFormatter.calendar = NSCalendar.current
dateFormatter.timeZone = TimeZone.current
let dt = dateFormatter.date(from: self)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = outGoingFormat
return dateFormatter.string(from: dt ?? Date())
}
}
Example how to use it:-
Note:- eventStartDate is the string which you have to converted in your format like this:- "2018-07-11T16:22:00.000Z"
let finalDate = eventStartDate.UTCToLocal(incomingFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ", outGoingFormat: "MMM d, yyyy h:mm a")

To convert a UTC Date to a local system date you could use the following Date extension:
extension Date {
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
// 1) Get the current TimeZone's seconds from GMT. Since I am in Chicago this will be: 60*60*5 (18000)
let timezoneOffset = TimeZone.current.secondsFromGMT()
// 2) Get the current date (GMT) in seconds since 1970. Epoch datetime.
let epochDate = self.timeIntervalSince1970
// 3) Perform a calculation with timezoneOffset + epochDate to get the total seconds for the
// local date since 1970.
// This may look a bit strange, but since timezoneOffset is given as -18000.0, adding epochDate and timezoneOffset
// calculates correctly.
let timezoneEpochOffset = (epochDate + Double(timezoneOffset))
// 4) Finally, create a date using the seconds offset since 1970 for the local date.
return Date(timeIntervalSince1970: timezoneEpochOffset)
}
}

For everyone using TimeZone objects.
I would advise you to create your TimeZone from identifier rather than abbreviation when you have the possibility.
This prevents errors caused by daylight saving.
To illustrate my point let's take an example.
You can instantiate like this
let timeZone = TimeZone(identifier: "Europe/Paris")
or like that
let timeZone = TimeZone(abbreviation: "CEST") or "UTC +2:00"
But this is time zone for summer CEST meaning Central Europe Summer Time
We have CET meaning Central Europe Time for winter which is "UTC +1:00"
You could manage daylight saving by your own with Date.isDaylightSavingsTime but this means more code and you don't have control on where your daylight saving sprang from.
"indicates whether the receiver is currently using daylight saving time" from official doc
All is that is to say favour TimeZone(identifier: ...)

You can use in swift 4/5
var myDate:String = "2020-02-18 14:30:57"
var convertedLocalTime:String = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let dt = dateFormatter.date(from: myDate) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
convertedLocalTime = dateFormatter.string(from: dt)
} else {
print("There was an error decoding the string")
}
print("convertedLocalTime--",convertedLocalTime)

Please try it:
func convertUTCToLocal(timeString: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
let timeUTC = dateFormatter.date(from: timeString)
if timeUTC != nil {
dateFormatter.timeZone = NSTimeZone.local
let localTime = dateFormatter.string(from: timeUTC!)
return localTime
}
return nil
}
func convertLocalToUTC(localTime: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = NSTimeZone.local
let timeLocal = dateFormatter.date(from: localTime)
if timeLocal != nil {
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
let timeUTC = dateFormatter.string(from: timeLocal!)
return timeUTC
}
return nil
}
var isTimeFromServer = true
var time:String!
var period:String!
let timeString = "6:59 AM" //Current UTC time
if isTimeFromServer {
print(convertUTCToLocal(timeString: timeString))
} else {
print(convertLocalToUTC(localTime: timeString))
}

If you need to convert timestamp you can use timezoneOffset like here:
if let dateStr = model.date, let dateInt = Int(dateStr) {
let timezoneOffset = TimeZone.current.secondsFromGMT()
let localDateInt = dateInt + timezoneOffset
let date = Date(timeIntervalSince1970: Double(localDateInt))
cell.dateLbl.text = date.toShortDateTimeString()
}

Related

Creating Date object from timestamp in Swift [duplicate]

I get a crash when running and it points at the dateFormmater.timezone.
The error in the console is:
Could not cast value of type 'Swift.Optional' (0x1192bf4a8) to 'NSTimeZone' (0x1192c0270).
the value of rowEvents.date is "1480134638.0"
Im trying to pull out a Unix timestamp from Firebase saved as a string. Convert it to Date and again save it as a string so I can post it on a cell label.
I got this code from StackOverflow. I plugged in my data and everything is all good until I run it. I guess everything is not all good...
if let lastUpdated : String = rowEvents.date {
let epocTime = TimeInterval(lastUpdated)! / 1000 // convert it from milliseconds dividing it by 1000
let unixTimestamp = NSDate(timeIntervalSince1970: epocTime) //convert unix timestamp to Date
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone() as TimeZone!
dateFormatter.locale = NSLocale.current // NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.date(from: String(describing: unixTimestamp))
let updatedTimeStamp = unixTimestamp
let cellDate = DateFormatter.localizedString(from: updatedTimeStamp as Date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.medium)
cell.subtitleLabel.text = cellDate
}
The result came from this code here:
let myTimeStamp = self.datePicker?.date.timeIntervalSince1970
let calendarDate = String(describing: myTimeStamp! /** 1000*/)
You can convert unixTimestamp to date using Date(timeIntervalSince1970:).
let unixTimestamp = 1480134638.0
let date = Date(timeIntervalSince1970: unixTimestamp)
If you want to display date in string with specific formate than you can use DateFormatter like this way.
let date = Date(timeIntervalSince1970: unixtimeInterval)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want
let strDate = dateFormatter.string(from: date)
The problem is the line dateFormatter.timeZone = NSTimeZone() as TimeZone!.
Simply use TimeZone instead of NSTimeZone like
dateFormatter.timeZone = TimeZone.current and your code will work.
You might also remove your / 1000 because 1480134638.0 looks more like seconds than milliseconds (since 1970).
Swift 4.1. I created a function. Just pass you timeStamp in function param and function will return data in string data type. You can add more properties to DateFormatter object.
func getDateFromTimeStamp(timeStamp : Double) -> String {
let date = NSDate(timeIntervalSince1970: timeStamp / 1000)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd MMM YY, hh:mm a"
// UnComment below to get only time
// dayTimePeriodFormatter.dateFormat = "hh:mm a"
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return dateString
}
Using playground all I did was this.
let epochTime = 1547855446
let newTime = Date(timeIntervalSince1970: TimeInterval(epochTime))
print(newTime)
Returns this - 2019-01-18 23:50:46 +0000
extension Double{
func convertDate(formate: String) -> String {
let date = (timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = NSLocale(localeIdentifier: "(your localization language)" ) as Locale //localization language
dateFormatter.dateFormat = formate //Specify your format that you want let
strDate = dateFormatter.string(from: date)
return strDate
}
}
//usage
let timeStamp:Double = Double(1595407043)
print(timeStamp.convertDate(formate: "EEEE dd/MM/YYY"))
This solution is valid for swift 3 -> 4.2 :
you can add an extension on the Double that returns the date formatted:
extension Double {
// returns the date formatted.
var dateFormatted : String? {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none //Set time style
dateFormatter.dateStyle = DateFormatter.Style.short //Set date style
return dateFormatter.string(from: date)
}
// returns the date formatted according to the format string provided.
func dateFormatted(withFormat format : String) -> String{
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date)
}
}
example on the above :
let timeStamp = 82749029.0
print(timeStamp. dateFormatted)
//output
//12/11/1994
let timeStamp = 82749029.0
print(timeStamp. dateFormatted(withFormat : "MM-dd-yyyy HH:mm"))
//output
//12-11-1994 13:04

How can I convert date string to time string?

I have a string that looks like this:
"date": "2022-06-30T02:15:00.000+07:00"
And I formatted it to convert to "HH:mm" like this:
func formatTime(string: String) -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
let date: Date? = dateFormatterGet.date(from: string)
return dateFormatterPrint.string(from: date ?? Date())
}
The result I want it returns is 09:15, but it returns 02:15.
Can someone tell me where I went wrong? Thank you
"2022-06-30T02:15:00.000+07:00" is the date in the time zone plus 7 hours from the UTC time zone. Than this date in UTC is ā€œ 2022-06-29T19:15:00Zā€
while dateFormatterPrint has a default locale configuration according to the phone settings
You need to set UTC timezone
In this case you might want to convert the DateTime to your local time first:
Convert To LocalTime:
func utcToLocal(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.string(from: date)
}
return nil
}
And then:
let utcTime = formatTime(string: "2022-06-30T02:15:00.000+07:00")
let localTime = utcToLocal(dateStr: utcTime)
print(localTime)
The Result:
09:15
I hope this help you solve your problem.

Swift 4 - How can I get dateTime format to Unix format?

Having some trouble making a function that gets the unix time from this very long date format that I get from an API.
func dateToUnix(date: String) -> Double {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-HH:mm"
let utcDate = dateFormatter.date(from: date)
guard let unixTime = utcDate?.timeIntervalSince1970 else { return 0.0 }
return unixTime
}
Here is the json format for the time
"startTime": "2018-07-10T01:00:00-05:00",
"endTime": "2018-07-10T02:00:00-05:00",
The "-05:00" is the timezone offset, not the hour and minutes.
func dateToUnix(string: String) -> Double {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let date = dateFormatter.date(from: string)
let unixTime = date?.timeIntervalSince1970 ?? 0.0
return unixTime
}

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
}

Xcode Swift am/pm time to 24 hour format

I am trying to convert an am/pm format time to a 24 hour format time
6:35 PM to 18:35
I tried this piece of code on playground but it doesn't seem to
work if I put the time alone
let dateAsString = "02/12/15, 6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH"
let date = dateFormatter.dateFromString(dateAsString) //returns nil
Does anyone know how to accomplish this?
Just convert it to a date using NSDateFormatter and the "h:mm a" format and convert it back to a string using the "HH:mm" format. Check out this date formatting guide to familiarize yourself with this material.
let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // fixes nil if device time in 24 hour format
let date = dateFormatter.dateFromString(dateAsString)
dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)
Swift 3
Time format 24 hours to 12 hours
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12)
output will be 12 hour formatted Date: 1:15 PM
Time format 12 hours to 24 hours
let dateAsString = "1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)
output will be 24 hour formatted Date: 13:15
Swift 3 *
Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes-
Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds
func timeConversion24(time12: String) -> String {
let dateAsString = time12
let df = DateFormatter()
df.dateFormat = "hh:mm:ssa"
let date = df.date(from: dateAsString)
df.dateFormat = "HH:mm:ss"
let time24 = df.string(from: date!)
print(time24)
return time24
}
Input
07:05:45PM
Output
19:05:45
Similarly
Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes-
Hours:Minutes:Seconds to Hours:Minutes:Seconds:AM/PM
func timeConversion12(time24: String) -> String {
let dateAsString = time24
let df = DateFormatter()
df.dateFormat = "HH:mm:ss"
let date = df.date(from: dateAsString)
df.dateFormat = "hh:mm:ssa"
let time12 = df.string(from: date!)
print(time12)
return time12
}
Input
19:05:45
Output
07:05:45PM
Below is the swift 3 version of the solution -
let dateAsString = "6:35:58 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm:ss a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm:ss"
let date24 = dateFormatter.string(from: date!)
print(date24)
Here is the answer with more extra format.
** Xcode 12, Swift 5.3 **
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16
dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM
dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000
dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000
dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000
dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM
dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000
dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00
//Output: Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm
// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)
Swift version 3.0.2 , Xcode Version 8.2.1 (8C1002) (12 hr format ):
func getTodayString() -> String{
let formatter = DateFormatter()
formatter.dateFormat = "h:mm:ss a "
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let currentDateStr = formatter.string(from: Date())
print(currentDateStr)
return currentDateStr
}
OUTPUT : 12:41:42 AM
Feel free to comment. Thanks
Use this function for date conversion, its working fine when your device in 24/12 hr format
See https://developer.apple.com/library/archive/qa/qa1480/_index.html
func convertDateFormatter(fromFormat:String,toFormat:String,_ dateString: String) -> String{
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = fromFormat
let date = formatter.date(from: dateString)
formatter.dateFormat = toFormat
return date != nil ? formatter.string(from: date!) : ""
}
Unfortunately apple priority the device date format, so in some cases against what you put, swift change your format to 12hrs
To fix this is necessary to use setLocalizedDateFormatFromTemplate instead of dateFormat an hide the AM and PM
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("HH:mm:ss a")
formatter.amSymbol = ""
formatter.pmSymbol = ""
formatter.timeZone = TimeZone(secondsFromGMT: 0)
var prettyDate = formatter.string(from: Date())
You can check a very useful post with more information detailed in
https://prograils.com/posts/the-curious-case-of-the-24-hour-time-format-in-swift
Here is code for other way around
For Swift 3
func amAppend(str:String) -> String{
var temp = str
var strArr = str.characters.split{$0 == ":"}.map(String.init)
var hour = Int(strArr[0])!
var min = Int(strArr[1])!
if(hour > 12){
temp = temp + "PM"
}
else{
temp = temp + "AM"
}
return temp
}
let calendar = Calendar.current
let hours = calendar.component(.hour, from: Date())
let minutes = calendar.component(.minute, from: Date())
let seconds = calendar.component(.second, from: Date())
I am using a function here in my case by which I am updating a label with the normal time format and after that I am storing the selected time's 24hr format to do some another tasks..
Here is my code...
func timeUpdate(sender: NSDate)
{
let timeSave = NSDateFormatter() //Creating first object to update time label as 12hr format with AM/PM
timeSave.timeStyle = NSDateFormatterStyle.ShortStyle //Setting the style for the time selection.
self.TimeShowOutlet.text = timeSave.stringFromDate(sender) // Getting the string from the selected time and updating the label as 1:40 PM
let timeCheck = NSDateFormatter() //Creating another object to store time in 24hr format.
timeCheck.dateFormat = "HH:mm:ss" //Setting the format for the time save.
let time = timeCheck.stringFromDate(sender) //Getting the time string as 13:40:00
self.timeSelectedForCheckAvailability = time //At last saving the 24hr format time for further task.
}
After writing this function you can call this where you are choosing the time from date/time picker.
Thanks,
Hope this helped.
this is similar to our friends answer: https://stackoverflow.com/a/43801717/2796837 but using all our internet friends ideas I came up with the following more complete singular solution:
let amPmFormat = "h:mm a"
let twentyFourHFormat = "HH:mm"
func hourMinuteParser(date: Date) -> KotlinInt{
let formatter = DateFormatter()
if DateFormatter.dateFormat(fromTemplate: "j",options:0, locale: Locale.current)!.contains("a") {
formatter.dateFormat = amPmFormat
}else{
formatter.dateFormat = twentyFourHFormat
}
let stringTime = formatter.string(from: date)
let time = formatter.date(from: stringTime)
formatter.dateFormat = twentyFourHFormat
let time24 = formatter.string(from: time!)
let timeWithoutSpecialCharacters = time24.replacingOccurrences(of: ":", with: "")
let int2 = Int32(timeWithoutSpecialCharacters) ?? 0
return KotlinInt(int: int2)
}
This will parse your time even independent of the format it comes and outputs it into HH:mm, you could change the third format change into whatever you would want.