Is it possible to add custom text in NSDateFormatter's format string?

后端 未结 3 872
醉酒成梦
醉酒成梦 2020-12-06 03:44

Suppose I want the date to look like this:

|1988|December|30|

How can add these to the dateFormatter or for that matter let the format be s

相关标签:
3条回答
  • 2020-12-06 04:32

    Updated for iOS 13, Swift 5, Xcode 11 and building on Martin R's answer

    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.locale = Locale.current
    dateFormatter.dateFormat = "dd' in the month of 'MMMM' in the year of 'yyyy"
    let stringDate = dateFormatter.string(from: Date())
    print(stringDate)
    
    // printed:
    // 7 in the month of October in the year of 2019
    

    P.S. If you wanted an apostrophe, then use: '' directly inside the string. For example "MMM d, ''yy" -> Nov 10, '19

    Extension:

    If you wanted to add ordinal indicators too (ex. the 'th' after '13th'), you can actually do it inside the date formatter string.

    So if you wanted Nov 10th, the code would be:

    /// Get date.
    let date = Date()
    
    /// Get just the day of the date. 
    let dayAsInt = Calendar.current.component(.day, from: date)
    
    /// Init the formatter.
    let dateFormatter = DateFormatter()
    
    /// Set the format string.
    /// Notice we include the 'MMM' to extract the month from the date, but we use a variable to get the 'th' part.
    dateFormatter.dateFormat = "MMM '\(dayAsInt.getStringWithOrdinalIndicatorIfPossible)'"
    let formattedDate = dateFormatter.string(from: date)
    
    /// Will print out Nov 10th or Apr 1st or whatever.
    

    Here's the extension I made to help:

    /// This variable only adds the ordinal indicator if the Int that is calling this function can be converted to an NSNumber.
    /// An ordinal indicator is the `rd` after `3rd` or the `st` after `1st`.
    var getStringWithOrdinalIndicatorIfPossible: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .ordinal
        return formatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
    
    0 讨论(0)
  • 2020-12-06 04:37

    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
    
    0 讨论(0)
  • 2020-12-06 04:44

    Swift Version:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat =  "EEEE' text here 'h:mm' and there 'a"
    
    0 讨论(0)
提交回复
热议问题