且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 iPhone 中将字符串值转换为日期?

更新时间:2022-11-18 18:57:28

我认为您的问题是未来的日期是星期四"、星期五"、...?

I gather that your problem is that future dates are coming in as "Thursday", "Friday", ...?

基本上,您需要将该文本转换为星期几(最简单的方法是如果阶梯",但如果您想对区域设置敏感,则可以使用更复杂的方案).然后找出今天的星期几并从第一个数字中减去它.如果结果为,则加 7.(如果结果为零,则可能意味着它指的是今天,或者可能意味着它指的是从今天开始的一周——如果你想要后者,如果结果为零或负,则加 7.)然后,要计算由输入的星期几表示的日期,请将上述计算结果乘以 ONE_DAY 与当前日期相加.

Basically, you need to convert that text to a day-of-week number (simplest approach is an "if ladder", though if you want to be locale-sensitive you can use a more complex scheme). Then figure out today's day-of-week number and subtract that from the first number. If the result is negative, add 7. (If the result is zero, it may mean that it refers to today, or it may mean it refers to a week from today -- if you want the latter, add 7 if the result is zero or negative.) Then, to compute the date represented by the input day of the week, add the above computed result multiplied times ONE_DAY to the current date.

你知道什么是如果***"?当然是:

You know what an "if ladder" is, of course:

if ([day isEqualToString:@"Sunday"]) {
    dayNumber = 1;
}
else if ([day isEqualToString:@"Monday"]) {
    dayNumber = 2;
}
else if ([day isEqualToString:@"Tuesday"]) {
....

要从当前日期获取星期几,请使用以下内容:

To get the day of week from the current date use something like:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
NSInteger todayNumber = [components weekday];

从 dayNumber 中减去 todayNumber.如果结果是否定的,则将结果加 7.然后该值会告诉您未来天"有多少天.是,从中你可以计算出它的日期.

Subtract todayNumber from dayNumber. If the result is negative, add 7 to the result. That value then tells you how many days in the future "day" is, and from that you can calculate it's date.