繁体   English   中英

使用NSDate获取日期

[英]Use of NSDate to get dates

我尝试了很多方法,但是始终失败,希望您能帮助我实现我想要的目标。

我正在制作一个iPad应用程序,一个视图中将有五个表,并且每个表都将以这种格式将日期作为标题/标题,例如星期一20

这五个表将在星期一至星期五。 这是我做不到的。 我想确定当前日期,然后突出显示今天的表格,显然每天都会更改。

例如,假设今天是星期四9日。 星期四表格突出显示,然后自动设置其他表格在星期四前后的日期。

想一想学校的时间表/计划者/日记。 周一至周五,每个标签都标有日期。

编辑:那如果我这样做呢? 如果我将此添加到您给我的代码中,则如果将TRUE(按下按钮)添加7天,就像在Apple示例示例中那样。 但是,我的问题是什么? 我用什么代替它? 我已经看到它在Apple的日历样本中使用了很多。

if (tableView == monTable){
        if(next == TRUE){
            [comps setDay:7];
            NSDate *date = [gregorian dateByAddingComponents:comps toDate:curDate  options:0];
        }
        else{
            [comps setWeekday:2];
        }
    }

您可以通过以下方式获取星期一至星期五的日期:

NSDate* curDate = [NSDate date]; // Get current date
NSCalendar* calendar = [NSCalendar currentCalendar];// Init calendar
NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components

    // Week days change from 1 to 7, Sunday is the 1st, Saturday - the last one.
for (int i = 2; i <= 6; i++){ 
    [comps setWeekday:i];
    NSDate *tDate = [calendar dateFromComponents:comps];
    NSLog(@"%@", tDate);
}

要确定要突出显示的日期(当前日期),您只需检查日期的工作日部分。

编辑: titleForHeaderInSection方法可能类似于:

- (NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section{
    NSDate* curDate = [NSDate date]; // Get current date
    NSCalendar* calendar = [NSCalendar currentCalendar];// Init calendar
    NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components

    // Week days change from 1 to 7, Sunday is the 1st, Saturday - the last one.
    if (tableView == monTable)
        [comps setWeekday:2];
    if (tableView == tueTable)
        [comps setWeekday:3];
    if (tableView == wedTable)
        [comps setWeekday:4];
    if (tableView == thuTable)
        [comps setWeekday:5];
    if (tableView == friTable)
        [comps setWeekday:6];

    NSDate *tDate = [calendar dateFromComponents:comps];
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"EEE, MMM d"];


    return [formatter stringFromDate:tDate];
}

暂无
暂无

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

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