NSDateFormatter涉及周数的问题 [英] NSDateFormatter issue involving week numbers

查看:196
本文介绍了NSDateFormatter涉及周数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的计算机(美国的区域设置)中,默认的短日期格式设置为1/5/13(月/日/年)。

On my machine (regional settings United States), the default "short" date format is set to "1/5/13" (month/day/year).

在系统偏好设置中,我已附加一个星期编号,1/5/13 1。

In the System Preferences, I have appended to it a week number, "1/5/13 1".

我的问题是这个代码,将字符串转换为日期:

My problem is this code, where I try to convert a string to a date:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [dateFormatter dateFromString:@"1/5/13 1"];
NSLog(@"Date: %@", date);

在我的机器上,输出:

Date: 2000-01-01 05:00:00 +0000

这是 2000 ,甚至不接近 2013

导致此问题的原因是什么? / p>

What is causing this problem?

推荐答案

我迟到了这个讨论,已经看到了一些解决方案,但我看到他们错了两个不兼容的日期格式元素一起使用。您的原始方法失败,因为您尝试获取您的日期的字符串不匹配 NSDateFormatterShortStyle 提供的字符串。

I'm late to this discussion, and have seen a number of solutions offered, but what I see wrong with them all is that two incompatible date format elements are being used together. Your original approach failed because the string from which you're attempting to get your date doesn't match what NSDateFormatterShortStyle provides for.

如果你要评估一年的那一周,那么你必须使用年度的大写形式;

If you're going to evaluate the week of the year, then you've got to use the capitalized form of the year; this provides for a "Week of Year" kind of calendar.

让我们重新使用您的原始代码,以包含新的格式:

Let's re-work your original code a bit to include the new format:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/YY w"];
NSDate *date = [dateFormatter dateFromString:@"1/5/13 1"];
NSLog(@"Date: %@", date);

请注意,我使用年份的大写形式。对于一年的一周,我得到:

Note that I'm using that capitalized form for the year. With 1 for the week of the year, I get this:

Date: 2013-01-05 08:00:00 +0000

以及一年中的星期2:

Date: 2013-01-12 08:00:00 +0000

和3:

Date: 2013-01-19 08:00:00 +0000

有意义,不是吗?日期中的日期增加7天,每次增加一年的一周。当然,这个时间是dorked,但我们从来没有讨论过在那个领域评估什么,是吗?

Makes sense, doesn't it? The day in the date increments by seven days with each increment by one of the week of year. The time's dorked, of course, but we never discussed anything to evaluate in that area, did we?

这篇关于NSDateFormatter涉及周数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆