How to Add Characters into Dateformatter

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()))

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

Java date format - including additional characters

Sure, with the SimpleDateFormat you can include literal strings:

Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

 "hh 'o''clock' a, zzzz"    12 o'clock PM, Pacific Daylight Time

How can I insert special characters in SimpleDateFormat?

You can escape literals using single quotes.

SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy 'at' hh:mma");

This will output Wed, 26 May 2010 at 11:17am

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

How to convert this string in a date with this format?

Basically you need an input date format and an output date format.

extension String {
var toDate: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddZ"

if let date = dateFormatter.date(from: self) {
let preposition = NSLocalizedString("of", comment: "Preposition of dates formatted")
dateFormatter.dateFormat = "dd '\(preposition)' MMMM"
let dateString = dateFormatter.string(from: date)
return dateString
}

return nil
}
}

I totally agree with rmaddy's comment to use setLocalizedDateFormatFromTemplate

The source of the date field symbols is unicode.org: Date Format Patterns

How do I ignore some characters when getting date from string using NSDateFormater? Also, is there any reference for NSDateFormatter?

NSDateformatter does not support days with ordinal indicators, but you could use a regular expression to strip the indicators

var dateString = "16th Sep 2015"
if let range = dateString.range(of: "(st|nd|rd|th)", options: .regularExpression) {
dateString.removeSubrange(range)
}
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd MMM yyyy"
let date = formatter.date(from: dateString)!
print(date)

Or in Objective-C

NSMutableString *dateString = [NSMutableString stringWithString:@"16th Sep 2015"];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(st|nd|rd|th)" options:nil error:nil];
[regex replaceMatchesInString:dateString options: nil range: NSMakeRange(0, 4) withTemplate:@""];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"d MMM yyyy";
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"%@", date);

Using Alphabetic Characters in SimpleDateFormat Pattern String

Surrounding the T with single quotes should work:

yyyy-MM-dd'T'hh:mm:ssZ

Quoting from the documentation (emphasis mine):

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

Your specific use case is even included as an example:

Date and Time Pattern            Result
-------------------------------------------------------------
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700

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")
}


Related Topics



Leave a reply



Submit