Как конвертировать строковое значение в дату в iPhone? - PullRequest
1 голос
/ 21 июля 2011

Я хочу преобразовать строковое значение в дату в моем проекте, потому что я получаю значение XML из Интернета. В XML-файле я получаю погодные условия, и все значения в этих погодных условиях получают текущую дату, но мое прогнозное условие не приходит в дату, оно указывается в виде строкового значения, например:

пятница суббота и воскресенье

Как это значение входит в мой прогнозный день, это строковое значение входит Day_of_week [Day_of_week] означает, что оно выглядит так:

пятница, суббота, воскресенье

Как я могу преобразовать это строковое значение с датой?

Это мой файл class.m контроллера

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    TWeatherCell *cell =(TWeatherCell *) [MyTableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"cell_%d", indexPath.row]];
    if (cell == nil) {
        //cell = [[[TWeatherCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:CellIdentifier] autorelease];
        cell = [[[TWeatherCell alloc] initWithFrame:CGRectZero reuseIdentifier:[NSString stringWithFormat:@"cell_%d", indexPath.row]] autorelease];
    }
        //ForecastCondition *cond=[forecastcond objectAtIndex:0];
    ForecastCondition *cond1=[forecastcond objectAtIndex:1];
    ForecastCondition *cond2=[forecastcond objectAtIndex:2];
    ForecastCondition *cond3=[forecastcond objectAtIndex:3];

    NSDate *today = [NSDate date]; // some valid date, let's say today is thursdaya
    NSDate *thursday = [today dateWithTimeInterval:1 *ONE_DAY sinceDate:cond1.Dayofweek];
    NSDate *friday = [today dateWithTimeInterval:2 * ONE_DAY sinceDate:cond2.Dayofweek];
    NSDate *saturday = [today dateWithTimeInterval:3 * ONE_DAY sinceDate:cond3.Dayofweek];
    if ([currentcond.Icon isEqualToString:@"http://\n"])
    {
        cell.weatherimage.image = [UIImage imageNamed:@"listIcon-H.png"];
    }
    else {
    NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:currentcond.Icon]];       
        NSLog(@"this is image from server:%@",imageData);
        cell.weatherimage.image = [UIImage imageWithData:imageData];
        [imageData release];
    }
    NSDateFormatter *date_formatter=[[NSDateFormatter alloc]init]; 
    [date_formatter setDateFormat:@"dd-MM-yyyy"]; 
    switch (indexPath.row) {
        case 0:
    NSLog(@"%d",indexPath.row);
            NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:currentcond.Icon]];
            NSLog(@"this is image from server:%@",imageData);
            cell.weatherimage.image = [UIImage imageWithData:imageData];
            [imageData release];

    cell.reportdate.text = _forecastInfo.CurrentDateTime;
    cell.conditionname.text = currentcond.Condition;
    cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",currentcond.Tempf,currentcond.Tempf];
    cell.twodirection.text = currentcond.WindCondition;
    cell.humidity.text = currentcond.Humidity;

    break;
        case 1:
            NSLog(@"%d",indexPath.row);

            cell.reportdate.text = cond1.Dayofweek;
            cell.conditionname.text = cond1.Condition;
            cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",cond1.Low,cond1.High];
            //NSDateFormatter *date_formatter=[[NSDateFormatter alloc]init]; 
//          [date_formatter setDateFormat:@"dd-MM-yyyy"]; 

            //[cond.Dayofweek dateWithTimeIntervalSinceNow:(60*60*24)*1];
            //NSDate *date1 = [date_formatter dateFromString:cond.Dayofweek]; 
            //NSDate *= NSDate *date1 ;
            //NSDate *date1 = [NSDate date];
            //NSString *strDate = [date_formatter stringFromDate:date1]; 


            break;
        case 2:

            NSLog(@"%d",indexPath.row);
            cell.reportdate.text = cond2.Dayofweek;
            cell.conditionname.text = cond2.Condition;
            cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",cond2.Low,cond2.High];
            break;
        case 3:
            NSLog(@"%d",indexPath.row);
            cell.reportdate.text = cond3.Dayofweek;
            cell.conditionname.text = cond3.Condition;
            cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",cond3.Low,cond3.High];
            break;
        default:
            NSLog(@"Out of Range ",indexPath.row);
            break;
    }
    return cell;
}

Ответы [ 4 ]

0 голосов
/ 21 июля 2011

Я понимаю, что ваша проблема в том, что будущие даты называются "четверг", "пятница", ...?

По сути, вам нужно преобразовать этот текст в число дня недели(самый простой подход - это «если лестница», хотя, если вы хотите быть чувствительным к локали, вы можете использовать более сложную схему).Затем вычислите сегодняшний номер дня недели и вычтите его из первого числа.Если результат равен отрицательный , добавьте 7. (Если результат равен нулю, это может означать, что оно относится к сегодняшнему дню, или это может означать, что оно относится к неделе с сегодняшнего дня - если вы хотите последнее,добавьте 7, если результат равен ноль или отрицательный .) Затем, чтобы вычислить дату, представленную входным днем ​​недели, добавьте вышеупомянутый вычисленный результат, умноженный на ONE_DAY, к текущей дате.

Подробнее

Вы знаете, что такое "если лестница", конечно:

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

Чтобы получить день недели от текущей даты, используйте что-то вроде:

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

Вычтите сегодня число из дня.Если результат отрицательный, добавьте 7 к результату.Затем это значение говорит вам, сколько дней будет в будущем «дне», и исходя из этого вы можете рассчитать его дату.

0 голосов
/ 21 июля 2011
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease]; 
[df setDateFormat:@"YYYY-MM-dd"]; 
NSDate* date = [df dateFromString:@"date string"];

NSLog(@"Converted date is %@",date);
0 голосов
/ 21 июля 2011

вы можете использовать "datefromstring" для вашей проблемы. здесь у меня есть пример для этого:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MMM yyyy "];
NSDate *date1 = [dateFormatter dateFromString:YourDate_String];
 NSLog(@"Date: %@",date1);
[dateFormatter release];

Надеюсь, это поможет вам.

0 голосов
/ 21 июля 2011

Используйте NSDateFormatter для преобразования между NSString и NSDate

...