简体   繁体   English

如何从 NSDate 变量中获取工作日和/或月份名称?

[英]How do I get weekday and/or name of month from a NSDate variable?

Alright.好的。 The problem we're having is that we have NSStrings filled with dates in the format of yyyyMMdd and what we want to do is to get the current weekday and name of month.我们遇到的问题是我们有 NSStrings 以 yyyyMMdd 格式填充日期,我们想要做的是获取当前工作日和月份名称。 The function dagOmvandlare converts the datestring to weekday and month.函数 dagOmvandlare 将日期字符串转换为工作日和月份。 The function is then called on viewDidload to name all our button-titles from english to swedish months.然后在 viewDidload 上调用该函数来命名我们所有的按钮标题,从英语到瑞典语月份。

our current solution is looking like this:我们目前的解决方案是这样的:

-(NSString *)dagOmvandlare:(id) suprDatum{

   NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
   dateFormatter.dateFormat = @"yyyyMMdd";

   NSDate *date = [dateFormatter dateFromString:suprDatum];


   NSString * monthString = [date descriptionWithCalendarFormat:@"%B"timeZone:nil
                                                         locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];

   if ([monthString isEqualToString:@"January"]) {
       monthString = @"Januari";
   }
   else
       if ([monthString isEqualToString:@"February"]) {
           monthString = @"Februari";
       }
       else
           if ([monthString isEqualToString:@"May"]) {
               monthString = @"Maj";
           }
           else
               if ([monthString isEqualToString:@"June"]) {
                   monthString = @"Juni";
               }
               else
                   if ([monthString isEqualToString:@"July"]) {
                       monthString = @"Juli";
                   }
                   else
                       if ([monthString isEqualToString:@"August"]) {
                           monthString = @"Augusti";
                       }
                       else
                           if ([monthString isEqualToString:@"October"]) {
                               monthString = @"Oktober";
                           }
                           else
                               if ([monthString isEqualToString:@"March"]) {
                                   monthString = @"Mars";
                               }

   return monthString;

}



- (void)viewDidLoad {
   [super viewDidLoad];

    [button3 setTitle:(NSString *)[self dagOmvandlare:self.datum1] forState:UIControlStateNormal];
    [button2 setTitle:(NSString *)[self dagOmvandlare:self.datum2] forState:UIControlStateNormal];
    [bmanad1 setTitle:(NSString *)[self dagOmvandlare:self.datum3] forState:UIControlStateNormal];

}

And what we've figured out so far is that the到目前为止我们已经弄清楚的是

NSString * monthString = [date descriptionWithCalendarFormat:@"%B"timeZone:nil
                                                         locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];

is not allowed to be used by Apples guidelines regarding non-public api's. Apple 的非公开 api 指南不允许使用它。 So the primary question is, what other way is there to get weekday and name of month out of our datestrings that contain dates with the format yyyyMMdd?所以主要问题是,还有什么其他方法可以从包含格式为 yyyyMMdd 的日期的日期字符串中获取工作日和月份名称?

There is no need to manually convert to the Swedish words.无需手动转换为瑞典语单词。 iPhone will do it for you. iPhone 会为你做这件事。 Try this:试试这个:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyyMMdd";
NSDate *date = [dateFormatter dateFromString:@"20111010"];

// set swedish locale
dateFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"];

dateFormatter.dateFormat=@"MMMM";
NSString *monthString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"month: %@", monthString);

dateFormatter.dateFormat=@"EEEE";
NSString *dayString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"day: %@", dayString);

Output:输出:

month: Oktober
day: Måndag

Simple Swift 3 extensions:简单的 Swift 3 扩展:

// Weekday
extension Date {
    func dayOfWeek() -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        return dateFormatter.string(from: self).capitalized
        // or capitalized(with: locale)
    }
}

print(Date().dayOfWeek()!) // Wednesday

// Month Name
extension Date {
    func monthName() -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMMM"
        return dateFormatter.string(from: self).capitalized
        // or capitalized(with: locale)
    }
}

print(Date().monthName()!) // October
NSString *strDate=@"20110407";
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"yyyyMMdd"];
NSDate *targetDate=[df dateFromString:strDate];
[df setDateFormat:@"EEEE MMMM dd, yyyy"];
NSString *s=[df stringFromDate:targetDate];

NSLog(@"Date: %@", s);

Hope this helps希望这可以帮助

NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];

[calendar release];

This might be useful可能有用

Another SO question which might help you How to find weekday from today's date using NSDate?另一个可能对您有帮助的问题How to find weekday from today's date using NSDate?

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:Date];

this dayName will be available in the locale of user.这个 dayName 将在用户的语言环境中可用。

As apple says, creating (and let ARC dispose) a formatter is expensive, so:正如苹果所说,创建(并让 ARC 处理)格式化程序非常昂贵,因此:

1) declare in your file: 1)在你的文件中声明:

private var localDateFormatter : DateFormatter?

..
extension Date {

2) use lazy approach: 2)使用惰性方法:

if localDateFormatter == nil{

        localDateFormatter = DateFormatter()

        let locale = Locale(identifier: "en_US_POSIX")

....}
    let newTime = localDateFormatter!.date(from: self)

if You have alla the stuff in one class, a static / let member would be nice.如果你在一个类中拥有所有东西,那么静态/让成员会很好。 (we cannot use vars in extensions... :( globals seems bad but no way...) (我们不能在扩展中使用 vars...:( globals 看起来很糟糕但没办法...)

You can use (For Swift and Türkiye localization):您可以使用(对于 Swift 和 Türkiye 本地化):

dateFormatter.locale = NSLocale(localeIdentifier: "tr_TR") as Locale
- (void) getMonthFromDate:(NSString *) stringDate
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:stringDate];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date]; // Get necessary date components

    NSLog(@"%lu", [components day]);
    NSLog(@"%lu %@",[components day],[[dateFormat monthSymbols] objectAtIndex:[components month]]);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM