Swift : How to convert String to string with time format?
You need 2 NSDateFormatter
s, one for dateFromString
, one for stringFromDate
let inFormatter = NSDateFormatter()
inFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
inFormatter.dateFormat = "HH:mm"
let outFormatter = NSDateFormatter()
outFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
outFormatter.dateFormat = "hh:mm"
let inStr = "16:50"
let date = inFormatter.dateFromString(inStr)!
let outStr = outFormatter.stringFromDate(date)
println(outStr) // -> outputs 04:50
Swift 5
let inFormatter = DateFormatter()
inFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
inFormatter.dateFormat = "hh:mm:ssa"
let outFormatter = DateFormatter()
outFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
outFormatter.dateFormat = "hh:mm a"
let inStr = "16:50"
let datess = inFormatter.date(from: inStr)!
let outStr = outFormatter.string(from: datess)
print(outstr)
How to convert string to date without change time swift
You can add a timezone to dateFormatter
dateFromat.timeZone = TimeZone(secondsFromGMT: 0)
Updated code:
let scheduleDate : String = "2020-01-25 20:11:00"
let dateFromat : DateFormatter = DateFormatter()
dateFromat.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFromat.timeZone = TimeZone.init(secondsFromGMT: 0)
let dateFromString = dateFromat.date(from: scheduleDate)
print(dateFromString as Any)
How to convert string date time format to another format using Swift
extension String {
func convertToDateFormate(current: String, convertTo: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = current
guard let date = dateFormatter.date(from: self) else {
return self
}
dateFormatter.dateFormat = convertTo
return dateFormatter.string(from: date)
}
}
convert to required formate as
let dateString = "12-10-2019"
let convertedDate = dateString.convertToDateFormate(current: "dd-MM-YYYY", convertTo: "YYYY-MM-dd")
Convert string to date in Swift
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)Finally create a new
Date
object and strip minutes and secondslet finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 10.12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
Converting a String to a Date in Swift
The date format needs to be for the string you are trying to convert, not the format you want back
so
formatter.dateFormat = "dd MM YYYY"
should be
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
Date to String [format string] String to Date in Swift
This should fix your issue
func convertStartDate(StartDate: Date) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyy-MM-dd '00':'00':'01' +0000"
let dateString = dateFormatter.string(from: StartDate)
dateFormatter.dateFormat = "yyy-MM-dd HH:mm:ss +0000"
let date = dateFormatter.date(from: dateString)
print(date as Any)
return date!
}
func convertEndDate(EndDate: Date) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyy-MM-dd '23':'59':'59' +0000"
let dateString = dateFormatter.string(from: EndDate)
dateFormatter.dateFormat = "yyy-MM-dd HH:mm:ss +0000"
let date = dateFormatter.date(from: dateString)
return date!
}
How Can I Make A Timer Using String In xCode
To keep things simple, here's the code. I have removed the functions that aren't relevant to the discussion - non-implemented buttons, etc.,
The simple idea is that you use numbers (Int / Double / whatever) to store variables that you are counting with, and then have helper functions to present the variable in different formats
import UIKit
class ChessTimer: UIViewController {
var timer = Timer()
var isTimerRunning = false
var storedTime : Int = 0 // use an integer to store the time
override func viewDidLoad() {
super.viewDidLoad()
if isTimerRunning == false {
runTimer()
}
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self,selector: (#selector(ChessTimer.updateTimer)),userInfo: nil, repeats: true)
isTimerRunning = true
}
@objc func updateTimer() {
// because we're storing the value in an Int, we don't need to convert it here
storedTime -= 1
if storedTime < 1 {
timer.invalidate()
// use the helper function to format the result for zero time as well as everything else
// that way, if you ever change it, you only have to change in one place
playerTimer1.text = prodTimeString(0)
playerTimer2.text = prodTimeString(0)
}
else {
playerTimer1.text = prodTimeString(storedTime)
}
}
func prodTimeString(_ time: Int) -> String {
// because there's only one parameter, and it's obvious, add '_' then you don't need the label when you call it
let prodMinutes = time / 60 % 60
let prodSeconds = time % 60
return String(format: "%02d:%02d", prodMinutes, prodSeconds)
}
}
Swift - How to convert String to Double
Swift 4.2+ String to Double
You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.
Note: The NSString doubleValue property is not recommended because it returns 0 if the value cannot be converted (i.e.: bad user input).
let lessPrecisePI = Float("3.14")
let morePrecisePI = Double("3.1415926536")
let invalidNumber = Float("alphabet") // nil, not a valid number
Unwrap the values to use them using if/let
if let cost = Double(textField.text!) {
print("The user entered a value price of \(cost)")
} else {
print("Not a valid number: \(textField.text!)")
}
You can convert formatted numbers and currency using the NumberFormatter
class.
let formatter = NumberFormatter()
formatter.locale = Locale.current // USA: Locale(identifier: "en_US")
formatter.numberStyle = .decimal
let number = formatter.number(from: "9,999.99")
Currency formats
let usLocale = Locale(identifier: "en_US")
let frenchLocale = Locale(identifier: "fr_FR")
let germanLocale = Locale(identifier: "de_DE")
let englishUKLocale = Locale(identifier: "en_GB") // United Kingdom
formatter.numberStyle = .currency
formatter.locale = usLocale
let usCurrency = formatter.number(from: "$9,999.99")
formatter.locale = frenchLocale
let frenchCurrency = formatter.number(from: "9999,99€")
// Note: "9 999,99€" fails with grouping separator
// Note: "9999,99 €" fails with a space before the €
formatter.locale = germanLocale
let germanCurrency = formatter.number(from: "9999,99€")
// Note: "9.999,99€" fails with grouping separator
formatter.locale = englishUKLocale
let englishUKCurrency = formatter.number(from: "£9,999.99")
Read more on my blog post about converting String to Double types (and currency).
Related Topics
Changing Selectedimage on Uitabbaritem in Swift
Different Cell in Tableview Swift 3
How to Get All the Sundays in Array of Date iOS
Swift - Using Cgcontext to Draw with Finger
How to Unwrap the Elements of an Array in Swift? (Ie. Array<Int> as Array<Int>)
How to Refresh a Timer in a Today Widget
How to Call Presentviewcontroller in Uiview Class
Random Image for Launch Screen
String to Double in Xcode 6's Swift
Xcode 12.5 Missing Entitlement Com.Apple.Developer.Associated-Appclip-App-Identifiers
Swift Extension and Enum for Color Schemes
How to Get the Nondecoded Attributes from a Decoder Container in Swift 4
How to Make an API Call When the User Terminates the App
How to Calculate a Random Cgpoint Which Does Not Touch a Uiview
How to Use a Generic Class Without the Type Argument in Swift
Cannot Convert Value of Type 'String.Type' to Expected Argument Type 'String!'
iOS 10 Issue: Uiscrollview Not Scrolling, Even When Contentsize Is Set