Swift 3 changing date format - ios

I want to get my Date in DD.MM.YYYY HH:mm:ss as a String.
I use the following extension:
extension Date {
var localTime: String {
return description(with: Locale.current)
}
}
and the following code when my datePicker changes:
#IBAction func datePickerChanged(_ sender: UIDatePicker) {
dateLabel.text = datePicker.date.localTime
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy hh:mm"
let TestDateTime = formatter.date(from: datePicker.date.localTime)
}
What am I doing wrong?

Your code is completely wrong. Just do the following:
#IBAction func datePickerChanged(_ sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy HH:mm"
dateLabel.text = formatter.string(from: sender.date)
}
This will convert the date picker's chosen date to a string in the format dd.MM.yyyy HH:mm in local time.
Never use the description method to convert any object to a user presented value.

Just used the function in your code(swift 4.2).
public func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
print(timeStamp)
return timeStamp
}
Thanks

Related

Convert Date to required format

I need to convert "2022-01-20T00:00:00.000Z" to "dd MMM yyy" format.
I have tried doing it as suggested in a stackoverflow answer but it returns nil
func convertDate(date:String)-> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "dd MMM yyy"
if let date = dateFormatterGet.date(from: String(date)) {
let convertedDate = dateFormatterPrint.string(from: date)
return convertedDate
} else {
print("There was an error decoding the string")
}
return "nil"
}
The fractional seconds are missing in the date format string. It's yyyy-MM-dd'T'HH:mm:ss.SSSZ.
And you are not using the date parameter. To avoid confusion with the local variable date rename it.
And you don't need two date formatters and it's highly recommended to set the Locale to a fixed value
func convertDate(dateString: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: dateString) {
dateFormatter.dateFormat = "dd MMM yyy"
return dateFormatter.string(from: date)
} else {
print("There was an error decoding the string")
return ""
}
}
got the answer
func convertDate(date:String)-> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "dd MMM yyy"
if let date = dateFormatterGet.date(from: String(date)) {
let convertedDate = dateFormatterPrint.string(from: date)
return convertedDate
} else {
print("There was an error decoding the string")
}
return "nil"
}
print(convertDate(date: "2022-01-20T00:00:00.000Z"))

String can't be parsed into Date "Swift"

I'm trying to parse the following String input "2020-04-05 19:02:02" into Date, which I'm using the following code to do that:
static func getDateFromString(_ dateStr: String) -> Date? {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd H:mm:ss"
dateFormater.timeZone = TimeZone(identifier: "UTC")
return dateFormater.date(from: dateStr)
}
The problem is that not working, it returns nil
Any suggestion? Thank you
Here you go, this works fine:
In dateString pass data in string format and for dateFormat pass format you want and to choose format use NSDateFormatter:
let expiryDateString = "2020-04-05 19:02:02"
let dateformat = "yyyy-MM-dd HH:mm:ss"
let expireDate = DateHelper.getDateFrom(expireDateString, dateformat)
static func getDateFrom(dateString: String,dateFormat: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = .current
guard let date = dateFormatter.date(from: dateString) else {return nil}
return date
}

Getting wrong time from dateformatter [duplicate]

This question already has answers here:
Dateformatter gives wrong time on conversation [duplicate]
(4 answers)
Closed 5 years ago.
I'm converting date fields from a XML file and these dates are stored in "yyyyMMddHHmmss" format. When I use date function of DateFormmater, I'm not getting the correct time. So for dateString "20150909093700", it returns "2015-09-09 13:37:00 UTC" instead of "2015-09-09 09:37:00". I'm doing this conversion before storing inside Core Data NSDate fields.
This is my code :
static func stringToDate(DateString dateString: String) -> NSDate? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
if let date = dateFormatter.date(from: dateString) {
return date as NSDate?
}
return nil
}
#user30646 -- see if this makes sense. Using your exact function:
func stringToDate(DateString dateString: String) -> NSDate? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
if let date = dateFormatter.date(from: dateString) {
return date as NSDate?
}
return nil
}
let dateString = "20150909093700"
let returnedDate = stringToDate(DateString: dateString)
print("Date without formatting or Time Zone: [", returnedDate ?? "return was nil", "]")
let dFormatter = DateFormatter()
dFormatter.timeZone = TimeZone(abbreviation: "EST")
dFormatter.dateStyle = .full
dFormatter.timeStyle = .full
print("Result with formatting and Time Zone: [", dFormatter.string(from: returnedDate as! Date), "]")
You are getting the "correct time" ... you just think you're not because you're looking at the wrong string representation of that date/time.

Convert NSDate to String in iOS Swift [duplicate]

This question already has answers here:
Convert NSDate to NSString
(19 answers)
Closed 5 years ago.
I am trying to convert a NSDate to a String and then Change Format. But when I pass NSDate to String it is producing whitespace.
let formatter = DateFormatter()
let myString = (String(describing: date))
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate)
you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here
for e.g , do like
let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date()) // string purpose I add here
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringDate = formatter.string(from: yourDate!)
print(myStringDate)
you get the output as
I always use this code while converting Date to String . (Swift 3)
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
and call like this . .
let today = Date()
today.toString(dateFormat: "dd-MM")
DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:
extension Date {
func asString(style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
}
This gives you the following styles:
short, medium, long, full
Example usage:
let myDate = Date()
myDate.asString(style: .full) // Wednesday, January 10, 2018
myDate.asString(style: .long) // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short) // 1/10/18
Your updated code.update it.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
After allocating DateFormatter you need to give the formatted string
then you can convert as string like this way
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
OutPut
01-Mar-2017
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")

Date picker shows a different date (1 day behined) from when picked

I have a UIDatePicker that is connected to a UILabel. I want the user to pick a birthday that is more than 18 years ago (age restriction). So I have this line to set the maximumDate value:
datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -18, toDate: NSDate(), options: [])
This line however causes the picker to show a 1 day behind the selected date. for example if I choose September 27, 1956 on the picker the label shows September 26, 1956 I believe it has to do with NSDate() using a different timezone one that is behind my local timezone.
switch dequeueFrom[indexPath.row] {
case .Birthday:
if let pickedBday = pickedBday,
let bday = NSDate.dateFromISOString(pickedBday) {
(cell as! RegisterTextFieldCell).content(bday.longFormattedString())
}
// dateFromISOSString is declared in an extension.swift
class func dateFromComponents(components: NSDateComponents) -> NSDate? {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
class func dateFromString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-SSS"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
func ISOStringFromDate() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return dateFormatter.stringFromDate(self).stringByAppendingString("Z")
}
class func dateFromISOString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
Any help with how I can make NSDate() be my local timezone so this one day behind issue can go away? Any help is greatly appreciated :)
The problem is in your method ISOStringFromDate because you are getting the local time and manually adding the Z (Z means UTC) to the string. Try like this when creating your iso8601:
extension NSDate {
var iso8601: String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter.stringFromDate(self)
}
}
and your code should be:
pickedDate.iso8601 // to get your date iso8601 string

Resources