【问题标题】:NSDate gives wrong yearNSDate 给出错误的年份
【发布时间】:2014-05-08 08:33:15
【问题描述】:

我正在尝试使用 NSDate,但它对我不起作用,我现在很困惑。所以我想要的基本东西是可行的,但它必须是今天,而不是从 2000 年开始。

所以我想要的是日期应该是今天的日期以及我的字符串 bU 和 eU 中的小时数,而不是 2000 年的日期和我的字符串小时数。

这是我的一段代码:

NSDate *localNotDate;

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"HH:mm"];

NSDate *bU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] beginUur]]; // This is a 24:00 format string
NSDate *eU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] eindUur]]; // This is a 24:00 format string

if (intForInsideForLoop == 0) { // Setup NSDate on first loop.
    localNotDate = bU; // This gives the date 2000-01-01 08:24
}

if (intForInsideForLoop < timesOnDay) {
    localNotDate = [localNotDate dateByAddingTimeInterval:(interval * 60)]; // Adds minutes to the date of today.

    NSDateFormatter *dtest = [[NSDateFormatter alloc] init];
    [dtest setTimeZone:[NSTimeZone localTimeZone]];
    [dtest setDateFormat:@"yyyy-MM-dd HH:mm"];

    NSLog(@"%@", [dtest stringFromDate:localNotDate]); // This gives the date 2000-01-01 08:24. it should be like It's Today thursday so 2014-05-08 08:24
}

【问题讨论】:

标签: ios objective-c nsdate


【解决方案1】:

我已经用 Martin 从帖子中给出的方法找到了我的问题的答案。此方法将像 (18:00) 这样的“时间”字符串转换为今天 18:00 的日期。

这里是:

- (NSDate *)todaysDateFromString:(NSString *)time
{
    // Split hour/minute into separate strings:
    NSArray *array = [time componentsSeparatedByString:@":"];

    // Get year/month/day from today:
    NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];

    // Set hour/minute from the given input:
    [comp setHour:[array[0] integerValue]];
    [comp setMinute:[array[1] integerValue]];

    return [cal dateFromComponents:comp];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2016-12-29
    • 1970-01-01
    • 2017-06-19
    • 2019-07-18
    相关资源
    最近更新 更多