Подтвердить что ты не робот

NSDate в полном стиле, но без года

Я работаю с Objective C для iPhone и имею NSDate, который я хочу отображать в полном стиле, но без года. Сейчас я использую код ниже, но он также показывает год, и я не хочу этого. Поскольку я хочу показать дату в правильном формате региона, я не могу просто удалить год в конце, так как в некоторых странах год не будет в конце, но посередине или в начале.

NSDate *testdate = [NSDate date];
NSDateFormatter *dateFormattertest = [[NSDateFormatter alloc] init];
[dateFormattertest setDateStyle:NSDateFormatterFullStyle];
[dateFormattertest setTimeStyle:NSDateFormatterNoStyle];
NSString *formattedDateString = [dateFormattertest stringFromDate:testdate];
NSLog(formattedDateString);

In US this give me:
Thursday, January 14, 2010

In Sweden this give me:
torsdag, 2010 januari 14

Какое решение для этого? И еще один вопрос, где я могу найти информацию о том, как использовать setDateFormat NSDateFormatter? Я не могу найти информацию о том, что означают разные буквы в API.

4b9b3361

Ответ 1

Я знаю, что это довольно старый вопрос, но это единственный, который я нашел на SO, который говорил о той же проблеме, что и я.

Ключевой способ использования здесь: dateFormatFromTemplate

Вместо установки стиля вы хотите установить формат как таковой:

NSDate *testdate = [NSDate date];

NSLocale *currentLocale = [NSLocale currentLocale];

// Set the date components you want
NSString *dateComponents = @"EEEEMMMMd";

// The components will be reordered according to the locale
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:currentLocale];
NSLog(@"Date format for %@: %@", [currentLocale displayNameForKey:NSLocaleIdentifier value:[currentLocale localeIdentifier]], dateFormat);

NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateFormat];

NSString *formattedDateString = [dateFormatter stringFromDate:testdate];
NSLog(formattedDateString);

Особая благодарность: http://oleb.net/blog/2011/11/working-with-date-and-time-in-cocoa-part-2/

Ответ 2

Взял @Joss отличный ответ на расширение Swift:

extension NSDate {
    func formattedFromCompenents(styleAttitude: NSDateFormatterStyle, year: Bool = true, month: Bool = true, day: Bool = true, hour: Bool = true, minute: Bool = true, second: Bool = true) -> String {
        let long = styleAttitude == .LongStyle || styleAttitude == .FullStyle
        var comps = ""

        if year { comps += long ? "yyyy" : "yy" }
        if month { comps += long ? "MMMM" : "MMM" }
        if day { comps += long ? "dd" : "d" }

        if hour { comps += long ? "HH" : "H" }
        if minute { comps += long ? "mm" : "m" }
        if second { comps += long ? "ss" : "s" }

        let format = NSDateFormatter.dateFormatFromTemplate(comps, options: 0, locale: NSLocale.currentLocale())
        let formatter = NSDateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

Ответ 3

Swift 3

    let template = "EEEEdMMM"

    let format = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current)
    let formatter = DateFormatter()
    formatter.dateFormat = format

    let now = Date()
    let whatYouWant = formatter.string(from: now) // ex: Sunday, Mar 5

Играйте с template в соответствии с вашими потребностями.

Doc и примеры здесь, чтобы помочь вам определить шаблон, который вы хотите.

Ответ 4

Swift 4

extension Date {
    public func formattedFromCompenents(styleAttitude: DateFormatter.Style, year: Bool = false, month: Bool = false, day: Bool = false, hour: Bool = false, minute: Bool = false, second: Bool = false, locale: Locale = Locale.current) -> String {
        let long = styleAttitude == .long || styleAttitude == .full
        let short = styleAttitude == .short
        var comps = ""

        if year { comps += long ? "yyyy" : "yy" }
        if month { comps += long ? "MMMM" : (short ? "MM" : "MMM") }
        if day { comps += long ? "dd" : "d" }

        if hour { comps += long ? "HH" : "H" }
        if minute { comps += long ? "mm" : "m" }
        if second { comps += long ? "ss" : "s" }
        let format = DateFormatter.dateFormat(fromTemplate: comps, options: 00, locale: locale)
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

Ответ 6

Здесь быстрый вариант, чтобы показать только дату месяца на ярлыке:

let todaysDate: NSDate = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM dd"
self.todayLabel.text = formatter.stringFromDate(todaysDate)