How to convert string value into date in iPhone?

2019-07-27 13:28发布

问题:

I want convert string value into date in my project because I am fetching XML value from web. In XML file I get weather condition and there all value in this weather condition I get current date but my forecastcondition is not come in date it comes in string value, like this:

friday saturday and sunday

Like this value are come in my forecast condition day this string value come in Day_of_week [Day_of_week] means it shows like this:

friday,saturday,sunday

How can I convert this string value with date?

This is my controller class.m file

- (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;
}

回答1:

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

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.

More detail

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];

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.



回答2:

Use NSDateFormatter to convert between NSString and NSDate



回答3:

you can use "datefromstring" for ur problem. here i've an example for this:

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

Hope this will help you.



回答4:

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease]; 
[df setDateFormat:@"YYYY-MM-dd"]; 
NSDate* date = [df dateFromString:@"date string"];

NSLog(@"Converted date is %@",date);