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

发布于 2024-10-31 03:48:59 字数 2523 浏览 0 评论 0原文

好吧。我们遇到的问题是 NSString 填充了日期 格式为 yyyyMMdd,我们想要做的是获取当前工作日和月份名称。函数 dagOmvandlare 将日期字符串转换为工作日和月份。然后在 viewDidload 上调用该函数来命名我们所有的按钮标题,从英语到瑞典语月份。

我们当前的解决方案如下所示:

-(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];

}

到目前为止,我们发现

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

苹果公司关于非公共 api 的指南不允许使用 。所以主要问题是,还有什么其他方法可以从包含 yyyyMMdd 格式的日期的日期字符串中获取工作日和月份名称?

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. The function dagOmvandlare converts the datestring to weekday and month. The function is then called on viewDidload to name all our button-titles from english to swedish months.

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. 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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

输什么也不输骨气 2024-11-07 03:48:59

无需手动转换为瑞典语单词。 iPhone 会为你做这件事。试试这个:

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

输出:

month: Oktober
day: Måndag

There is no need to manually convert to the Swedish words. iPhone will do it for you. 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
魔法少女 2024-11-07 03:48:59

简单的 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

Simple Swift 3 extensions:

// 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
清醇 2024-11-07 03:48:59
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);
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);
妳是的陽光 2024-11-07 03:48:59

希望这会有所帮助

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];

可能有用

另一个SO问题可能会帮助你如何使用 NSDate 从今天的日期查找工作日?

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?

哆兒滾 2024-11-07 03:48:59
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:Date];

this dayName 将在用户的区域设置中可用。

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

this dayName will be available in the locale of user.

落日海湾 2024-11-07 03:48:59

正如苹果所说,创建(并让 ARC 处理)格式化程序的成本很高,因此:

1)在文件中声明:

private var localDateFormatter : DateFormatter?

..
extension Date {

2)使用惰性方法:

if localDateFormatter == nil{

        localDateFormatter = DateFormatter()

        let locale = Locale(identifier: "en_US_POSIX")

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

如果您在一个类中拥有所有内容,那么 static / let 成员会很好。 (我们不能在扩展中使用变量...:(全局变量似乎很糟糕,但没办法...)

As apple says, creating (and let ARC dispose) a formatter is expensive, so:

1) declare in your file:

private var localDateFormatter : DateFormatter?

..
extension Date {

2) use lazy approach:

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

述情 2024-11-07 03:48:59

您可以使用(对于 Swift 和 Türkiye 本地化):

dateFormatter.locale = NSLocale(localeIdentifier: "tr_TR") as Locale

You can use (For Swift and Türkiye localization):

dateFormatter.locale = NSLocale(localeIdentifier: "tr_TR") as Locale
╄→承喏 2024-11-07 03:48:59
- (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]]);

}
- (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]]);

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文