How to change date format in iOS
the dateFormat = @"yyyy-MM-dd'T'HH:mm:ssxxx"
to convert your NSString
to NSDate
Code:
NSString *myString = @"2015-06-08T00:00:00+02:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssxxx";
NSDate * myDate = [formatter dateFromString:myString];
formatter.dateFormat = @"dd/MM/yyyy";
NSString *newString = [formatter stringFromDate:myDate];
NSLog(@"%@",newString);
See ICU Formatting Dates and Times to format DateTime
How to convert date format from dd/MM/YYYY to YYYY-MM-dd in swift
First changes your year
formatter with yyyy
and instead of using two NSDateFormatter
use just one like this
let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/yyyy"
let showDate = inputFormatter.dateFromString("07/21/2016")
inputFormatter.dateFormat = "yyyy-MM-dd"
let resultString = inputFormatter.stringFromDate(showDate!)
print(resultString)
For Swift3 and later
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let date = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy-MM-dd"
let resultString = dateFormatter.string(from: date!)
print(resultString)
Swift date format returning wrong date
The code in your question is muddled up. You try to convert a string into a string in the first example and something unspecified into a Date
in the second example.
Here's how to convert a Date
into a String
:
import Foundation
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
let string: String = formatter.string(from: Date())
print(string) // prints for example 2020-10-18T10:54:07+01:00
Here's how to convert a string into a date
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date: Date = formatter.date(from: "2020-10-18 10:59:56+0100")! // In real life, handle the optional properly
print(date) // prints 2020-10-18 09:59:56 +0000
When you print a Date directly, it automatically uses UTC as the time zone. This is why it changed it in the code above.
In the examples, I explicitly specified the type of string
and date
to show what type they are. Type inference means you can omit these in normal code.
As a general rule when handling dates:
- always use
Date
in your code.Date
is a type that stores the number of seconds since Jan 1st 1970 UTC. - Only convert dates to strings when displaying them to the user or communicating with an external system.
- When calculating periods etc, always use a Calendar to get things like date components and intervals in units other than seconds. You might think to get "the same time tomorrow" you could just add 24 * 60 * 60 to a
Date
but in many countries, like mine, that will work on only 363 days in the year.Calendar
will correctly handle things like daylight saving and leap years.
Changing date format on iOS
To convert from 1 string to the other use the following
NSString *inputString = @"2012-06-26 12:00:00 +0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss z"];//input
NSDate *date = [formatter dateFromString:inputString];
[formatter setDateFormat:@"MMM dd, yyyy hh:mm:ss a"];
NSString *outputString = [formatter stringFromDate:date];
NSLog(@"output : %@",outputString);
iOS 15.4 Date Format Sep now Sept
Assuming this problem occurs just for September and on iOS 15.4
, then
a quick work around, is to replace "Sept" with "Sep", using
dateTextField.text = dateFormatter.string(from: (datePicker?.date )!)
if dateTextField.text.contains("Sept") {
dateTextField.text = dateTextField.text.replacingOccurrences(of: "Sept", with: "Sep")
}
Date Format in Swift
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")
}
How to convert date from server in Swift?
You need to learn a bit more about how to set the dateFormat
string. You forgot the Z
in the string. Also as a warning. Creating date formatter objects is extremely expensive. Do not create a new one for every date you want to format. Be sure to cache it and reuse it.
import Foundation
let serverDateFormatter:DateFormatter = {
let result = DateFormatter()
result.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ"
result.locale = Locale(identifier: "en_US_POSIX")
result.timeZone = TimeZone(secondsFromGMT: 0)
return result
}()
let date = "2021-09-08T20:52:47.001Z"
let dateformat = serverDateFormatter.date(from: date)
print(dateformat as Any)
Related Topics
Xcode 4.2 with Arc: Will My Code Run Even on iOS Devices with Firmware Older Than 5.0
Swift4: Callback Url Not Approved for This Client Application
How to Use Pod in Notification Service Extension
How to Implement a "Rate Us" Feature in a Phonegap App
How to Record and Save at 240 Frames Per Second
Fix Cursor Size for Modified Paragraph Spacing in Uitextview
How Come My Drawing Code Keeps Resulting in Fuzzy Shapes
How to Pair And/Or Bond to Ble on iOS Using Swift Code and an Hm-10 So Data Sent Is Encrypted
Where Is Uiview.Init() Documented
How to Animate Uilabel's Textcolor Change
Use Elcimagepickercontroller to Pick Video
Using Delegates to Transfer Data from One Tableview to Another
Uitextview - Can't Set Underline or Strikethrough Attributes on Text
Fetch() Doing Get Instead of Post on React-Native (iOS)