Is it possible to add custom text in NSDateFormatter's format string?
You can insert arbitrary text (enclosed in single quotes) in the date format, for example.
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"dd' in the month of 'MMMM' in the year of 'yyyy"];
NSString *s = [fmt stringFromDate:[NSDate date]];
Result:
09 in the month of July in the year of 2013
How can I write a custom Date Format with string into it?
You have to wrap it into quotes '
, e.g.
"dd 'de' MMMM, yyyy"
From Date Format Patterns:
Literal text, which is output as-is when formatting, and must closely match when parsing. Literal text can include:
- Any characters other than A..Z and a..z, including spaces and punctuation.
- Any text between single vertical quotes ('xxxx'), which may include A..Z and a..z as literal text.
You can also let the formatter generate the de
:
let locale = Locale(identifier: "pt-BR")
let dateFormatter = DateFormatter()
let dayFormat = DateFormatter.dateFormat(fromTemplate: "d MMMM", options: 0, locale: locale)!
dateFormatter.dateFormat = dayFormat + ", yyyy"
dateFormatter.locale = locale
print(dateFormatter.string(from: Date())) // 7 de junho, 2017
NSDateFormatter with custom string inbetween
Your format could be something like
M/dd/yyyy' at 'hh:mm a
3/24/2016 at 12:00 AM
You can check this link for further details.
Format String Output String
M/d/y 11/4/2012
MM/dd/yy 11/04/12
MMM d, ''yy Nov 4, '12
MMMM November
E Sun
EEEE Sunday
'Week' w 'of 52' Week 45 of 52
'Day' D 'of 365' Day 309 of 365
QQQ Q4
QQQQ 4th quarter
m 'minutes past' h 9 minutes past 8
h:mm a 8:09 PM
HH:mm:ss's' 20:09:00s
HH:mm:ss:SS 20:09:00:00
h:mm a zz 8:09 PM CST
h:mm a zzzz 8:09 PM Central Standard Time
yyyy-MM-dd HH:mm:ss Z 2012-11-04 20:09:00 -0600
You can combine any of the options as per your requirements.
How to add characters into dateFormatter
Add single quotes
xFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-04:00"
From the documentation:
... This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.
Source: Unicode.org: Date Format Patterns
Edit:
Be aware that the time zone is just an amendment to the string, it's not considered by the date formatter.
To consider the time zone you have to set the timeZone
of the formatter
xFormatter.timeZone = TimeZone(secondsFromGMT: -14400)
In iOS 10.0+ and macOS 10.12+ there is a more convenient way to create an ISO8601 string
let isoFormatter = ISO8601DateFormatter()
isoFormatter.timeZone = TimeZone(secondsFromGMT: -14400)
isoFormatter.formatOptions = .withInternetDateTime
print(isoFormatter.string(from: Date()))
NSDateFormatter formats hours in range out of 0-24 with some international settings
Based on comment of rmaddy and Rob the right solution in this situation is to specify "en_US_POSIX" locale for all formatters involved in serialisation NSDate objects.
So snipped posted in question part should be:
#define DATE_FORMAT "yyyy-MM-dd HH:mm:ssZ"
formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @DATE_FORMAT;
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
return [formatter stringFromDate:value];
For everybody who have same issue link posted by Rob would be extremely useful.
See Technical Q&A 1480. I would recommend you to read it before applying this solution to your code.
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")
}
Escape NSDateFormatter String
You can escape text by enclosing it in single quotes:
[dateFormater setDateFormat:@"dd/MM/yyyy 'at' HH:mm"];
From the docs:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"formattedDateString: %@", formattedDateString);
// For US English, the output may be:
// formattedDateString: 2001-01-02 at 13:00
Set Formatted NSDate in UILabel text
Check my answer to this question, you will get all the info you need here:
Date formatter for the google calender API
Related Topics
Add Uitapgesturerecognizer to Uitextview Without Blocking Textview Touches
Load a .Tmx (Tiled Map) in Sprite Kit
The Bundle's Info.Plist Does Not Contain a Cfbundleversion Key or Its Value Is Not a String
How to Read Incoming Sms by Using Application in iOS
Uitableviewcellaccessorycheckmark and Autolayout Constraints
Visually Modifying a Uitoolbar from Xcode Storyboard
Hit Detection When Drawing Lines in iOS
Delete and Update Data in Core Data in iOS
Multiple Uicollectionview in One Controller
Protocol Extension, Mutating Function
iPhone Camera, How to Avoid Cameraoverlay on Preivew View; How to Know When Entering Preview View
How to Find the Kind of Errors a Method May Throw and Catch Them in Swift
Swift Put Multiple Iboutlets in an Array
Track Cellular Data Usage Using Swift
How to Find Out What View a Touch Event Ended At