How will I convert this datetime from the date?
From this: 2016-02-29 12:24:26
to: Feb 29, 2016
So far, this is my code and it returns a nil value:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date: NSDate? = dateFormatter.dateFromString("2016-02-29 12:24:26")
print(date)
This may be useful for who want to use dateformatter.dateformat;
if you want 12.09.18 you use dateformatter.dateformat = "dd.MM.yy"
Wednesday, Sep 12, 2018 --> EEEE, MMM d, yyyy
09/12/2018 --> MM/dd/yyyy
09-12-2018 14:11 --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM --> MMM d, h:mm a
September 2018 --> MMMM yyyy
Sep 12, 2018 --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000 --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000 --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18 --> dd.MM.yy
10:41:02.112 --> HH:mm:ss.SSS
Here are alternatives:
Era: G (AD), GGGG (Anno Domini)
Year: y (2018), yy (18), yyyy (2018)
Month: M, MM, MMM, MMMM, MMMMM
Day of month: d, dd
Day name of week: E, EEEE, EEEEE, EEEEEE
You have to declare 2 different NSDateFormatters, the first to convert the string to a NSDate and the second to print the date in your format.
Try this code:
let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))
Swift 3 and higher:
From Swift 3 NSDate class has been changed to Date and NSDateFormatter to DateFormatter.
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
print(dateFormatterPrint.string(from: date))
} else {
print("There was an error decoding the string")
}
Swift - 5.0
let date = Date()
let format = date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss") // Set output format
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: self)
}
}
Swift - 4.0
2018-02-01T19:10:04+00:00 Convert Feb 01,2018
extension Date {
static func getFormattedDate(string: String , formatter:String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: Date? = dateFormatterGet.date(from: "2018-02-01T19:10:04+00:00")
print("Date",dateFormatterPrint.string(from: date!)) // Feb 01,2018
return dateFormatterPrint.string(from: date!);
}
}
Swift 3 and higher
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.locale = Locale.current
print(dateFormatter.string(from: date)) // Jan 2, 2001
This is also helpful when you want to localize your App. The Locale(identifier: ) uses the ISO 639-1 Code.
See also the Apple Documentation
Swift 3 version with the new Date object instead NSDate:
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy"
let date: Date? = dateFormatterGet.date(from: "2017-02-14 17:24:26")
print(dateFormatter.string(from: date!))
EDIT: after mitul-nakum suggestion
Convert #BatyrCan answer to Swift 5.3 with extra formats. Tested in Xcode 12.
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
//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 3
let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)
I solved my problem to the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'(e.g 2018-06-15T00:00:00.000Z) with this:
func formatDate(date: String) -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
// dateFormatter.locale = Locale(identifier: "en_US") //uncomment if you don't want to get the system default format.
let dateObj: Date? = dateFormatterGet.date(from: date)
return dateFormatter.string(from: dateObj!)
}
iOS 15.0+
iPadOS 15.0+,
macOS 12.0+,
Mac Catalyst 15.0+,
tvOS 15.0+,
watchOS 8.0+,
Xcode 13.0+
Use formatted(date:time:)
let now = Date.now
let date = now.formatted(date: .abbreviated, time: .omitted)
Instead of .abbreviated, you may use another DateStyle such as .long, .numeric or define a custom format.
SwiftUI
Text(myDate, format: Date.FormatStyle(date: .numeric, time: .omitted))
or simply use:
Text(myDate, style: .date)
Reference
formatted(date:time:)
init(_:format:)
Text.DateStyle
Swift 4, 4.2 and 5
func getFormattedDate(date: Date, format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: date)
}
let formatingDate = getFormattedDate(date: Date(), format: "dd-MMM-yyyy")
print(formatingDate)
Swift Version: 5.6 + Above
DateFormatter’s dateFormatter property is used to format Date with a custom String Pattern.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let date = dateFormatter.string(from: datePicker.date)
print(date)
//Feb 28, 2022
If you want anything that shouldn’t be formatted and printed, then use single quotes around that word. Like; ‘at’
dateFormatter.dateFormat = "MMM dd, yyyy 'at' hh:MM a"
// May 29, 2022 at 12:05 PM
These are all possible Patterns to Format Date, Time & Time Zone.
Swift 3 with a Date extension
extension Date {
func string(with format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
Then you can use it like so:
let date = Date()
date.string(with: "MMM dd, yyyy")
If you want to parse date from "1996-12-19T16:39:57-08:00", use the following format "yyyy-MM-dd'T'HH:mm:ssZZZZZ":
let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.date(from: string)
from Apple https://developer.apple.com/documentation/foundation/dateformatter
Another interessant possibility of format date. This screenshot belongs to Apple's App "News".
Here is the code:
let dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "EEEE"
let stringDay = dateFormat1.string(from: Date())
let dateFormat2 = DateFormatter()
dateFormat2.dateFormat = "MMMM"
let stringMonth = dateFormat2.string(from: Date())
let dateFormat3 = DateFormatter()
dateFormat3.dateFormat = "dd"
let numDay = dateFormat3.string(from: Date())
let stringDate = String(format: "%#\n%# %#", stringDay.uppercased(), stringMonth.uppercased(), numDay)
Nothing to add to alternative proposed by lorenzoliveto. It's just perfect.
let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEEE\nMMMM dd"
let stringDate = dateFormat.string(from: Date()).uppercased()
import UIKit
// Example iso date time
let isoDateArray = [
"2020-03-18T07:32:39.88Z",
"2020-03-18T07:32:39Z",
"2020-03-18T07:32:39.8Z",
"2020-03-18T07:32:39.88Z",
"2020-03-18T07:32:39.8834Z"
]
let dateFormatterGetWithMs = DateFormatter()
let dateFormatterGetNoMs = DateFormatter()
// Formater with and without millisecond
dateFormatterGetWithMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatterGetNoMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
for dateString in isoDateArray {
var date: Date? = dateFormatterGetWithMs.date(from: dateString)
if (date == nil){
date = dateFormatterGetNoMs.date(from: dateString)
}
print("===========>",date!)
}
just use below function to convert date format:-
let convertedFormat = convertToString(dateString: "2019-02-12 11:23:12", formatIn: "yyyy-MM-dd hh:mm:ss", formatOut: "MMM dd, yyyy") //calling function
print(convertedFormat) // feb 12 2019
func convertToString (dateString: String, formatIn : String, formatOut : String) -> String {
let dateFormater = DateFormatter()
dateFormater.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
dateFormater.dateFormat = formatIn
let date = dateFormater.date(from: dateString)
dateFormater.timeZone = NSTimeZone.system
dateFormater.dateFormat = formatOut
let timeStr = dateFormater.string(from: date!)
return timeStr
}
To convert 2016-02-29 12:24:26 into a date, use this date formatter:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
Edit: To get the output Feb 29, 2016 use this date formatter:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
For Swift 4.2, 5
Pass date and format as whatever way you want.
To choose format you can visit, NSDATEFORMATTER website:
static func dateFormatter(date: Date,dateFormat:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: date)
}
Place it in extension and call it like below. It's easy to use throughout the application.
self.getFormattedDate(strDate: "20-March-2019", currentFomat: "dd-MMM-yyyy", expectedFromat: "yyyy-MM-dd")
Implementation
func getFormattedDate(strDate: String , currentFomat:String, expectedFromat: String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = currentFomat
let date : Date = dateFormatterGet.date(from: strDate) ?? Date()
dateFormatterGet.dateFormat = expectedFromat
return dateFormatterGet.string(from: date)
}
From iOS 15 use something like this:
extension Date {
var string: String {
if #available(iOS 15.0, *) {
return self.formatted(date: .complete, time: .complete)
} else {
return self.description
}
}
}
Here is a full date format extension for swift
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: self)
}
func getFormattedDate(style: DateFormatter.Style) -> String {
let dateformat = DateFormatter()
dateformat.dateStyle = style
return dateformat.string(from: self)
}
}
Usage
myDate.getFormattedDate(style: .medium) //medium, short, full, long
OR
myDate.getFormattedDate(format: "yyyy/MM/dd HH:mm:ss")
swift 3
func dataFormat(dataJ: Double) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
let date = Date(timeIntervalSince1970: dataJ)
return (dataJ != nil) ? "Today, \(dateFormatter.string(from: date))" : "Date Invalid"
}
I recommend to add timezone by default. I will show an example for swift 5
1. new an extension file Date+Formatter.swift
import Foundation
extension Date {
func getFormattedDateString(format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone.current
return dateFormatter.string(from: self)
}
}
Usage example
let date = Date()
let dateString = date.getFormattedDateString(format: "yyyy-MM-dd HH:mm:ss")
print("dateString > \(dateString)")
// print
// dateString > 2020-04-30 15:15:21
class Utils {
class func dateFormatter(_ date: Date, _ format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: date)
}
}
print(Utils.dateFormatter(Date(), "EEEE, MMM d, yyyy"))
Create class name Utils import same function and you can use globally accesss any where with your date and formate
Related
This question already has answers here:
What is happening to the year?
(1 answer)
Difference between 'YYYY' and 'yyyy' in NSDateFormatter
(4 answers)
Closed 1 year ago.
extension Date {
func toString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, Y (E)"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
return dateFormatter.string(from: self)
}
}
extension String {
func toDate() -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, Y (E)"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
return dateFormatter.date(from: self)!
}
}
That is my code.
I want to convert my string value into a right date value. The results i’m getting are totally different form what i want.
Here is an example:
String : September 09, 2021 (Thu)
Converted Date : 2020-12-24 00:00:00 +0000
I want it to be like this:
Converted Date : September 09, 2021 (Thu) (or 2021-09-09 00:00:00 +0000)
Can you change
dateFormatter.dateFormat = "MMMM dd, Y (E)"
To:
dateFormatter.dateFormat = "MMMM dd, yyyy (E)"
You pass the full year in String: September 09, 2021 (Thu) so you need to get yyyy to the right way.
extension String {
func toDate() -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy (E)"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
return dateFormatter.date(from: self)!
}
}
here you can do what you want:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy (E)" // here is your foramt
dateFormatter.timeZone = TimeZone(identifier: "UTC")
guard let date = dateFormatter.date(from: "September 09, 2021 (Thu)") else {
fatalError()
}
print(date) // output: 2021-09-09 00:00:00 +0000
Note that, the time zone which you choosed, should matched to your device time zone.
Replace Your Function with Following Code
extension Date {
func toString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy (E)"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
return dateFormatter.string(from: self)
}
}
extension String {
func toDate() -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy (E)"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
return dateFormatter.date(from: self)!
}
}
There was slight variance of in your dateFormat in your toDate() Function
Replaced MMM from MMMM
Replaced yyyy from Y
I don't know why it was showing different date but now it should work😅
can you please help me with that topic?
from the API i get the following date as a string: 2021-05-21T14:35:15.647+02:00
How can i convert this to a date object, so that i can format it?
I tried it in different ways as subscribed here in stackoverflow or in other tutorials, like this:
let date = "2021-05-21T14:35:15.647+02:00"
func formatStringDate(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let newDate = dateFormatter.date(from: date)
dateFormatter.setLocalizedDateFormatFromTemplate("MMMM d, yyyy")
return dateFormatter.string(from: newDate!)
}
var newDate = formatStringDate(date: date)
print(newDate)
or
let timestampString = "2018-12-09T11:08:48-05:00"
if let date = isoDateFormatter.date(from: timestampString) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM, dd, yyyy h:mm a"
let dateFormattedString = dateFormatter.string(from: date)
print(dateFormattedString) // December, 09, 2018 11:08 AM
} else {
print("not a valid date")
}
But it´s not working.
Thanks for your help
Thanks for your help, i got the following snippet to work:
let dateString = "2021-05-21T14:35:15.647+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate
]
let date = inputFormatter.date(from: dateString)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.YYYY"
print(dateFormatter.string(from: date!))
Thanks
picked date and time from datepicker and need to converted to required from before sending to the server.
not able to convert to the required from.
func convertToUTC(dateToConvert:String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM d yyyy HH:mm:ss.SSS'Z"
let convertedDate = formatter.date(from: dateToConvert)
formatter.timeZone = TimeZone(identifier: "UTC")
return formatter.string(from: convertedDate!)
}
requred date form is Sat Aug 1 2020 23:38:56 GMT+0530
You can simply create two date formats, one to parse the input date string and another to convert the date to your server date format:
extension Formatter {
static let inputDate: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE MMM d yyyy HH:mm:ss.SSSZ"
return dateFormatter
}()
static let serverDate: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'xxxx"
return dateFormatter
}()
}
func convertToServer(input: String) -> String? {
guard let date = Formatter.inputDate.date(from: input) else { return nil }
return Formatter.serverDate.string(from: date)
}
convertToServer(input: "Sat Aug 1 2020 23:38:56.123Z") // "Sat Aug 1 2020 20:38:56 GMT-0300"
I have this datetime format output in UILabel
datefrom.text = "2010-12-05 00:00:00"
But I want to display this date format into something simple like this
5 December 2010 or Dec 5, 2010
I use this code to display the date but it display the today's date which is 5 April 2017
date.swift
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "d MMM yyyy"
let result = formatter.string(from:date)
datefrom.text = result
Any solution ?
Thanks.
The DateFormatter will help you do this!
Step 1: Convert your string to a date type
func convertStringToDate(string: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.date(from: dateString)
}
Step 2: Convert your date to your expected format
func convertDateToString(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d MMM yyyy"
return dateFormatter.string(from: date)
}
That's it!
let dateString = "2010-12-05 00:00:00"
let date = convertStringToDate(string: dateString)
let result = convertDateToString(date: date!)
datefrom.text = result
// 5 Dec 2010
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.