Pergunta

I have an NSString that is 05/08/2014. I want to convert that to an NSDate. However, I also need to add in time, so that the resulting NSDate looks like this:

Thu, 8 May 2014 00:00:00 -0500

The time is not important, I just need it to show midnight at the designated timezone.

I have tried:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

        [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss zzz"];
        NSDate *dateFromString = [[NSDate alloc] init];
        dateFromString = [dateFormatter dateFromString:textdate.text];
        [dateFormatter release];
        NSLog(@"%@", dateFromString);

But the date comes back as (null).

Foi útil?

Solução

Your date format is wrong for the first conversion. What you need is first to convert from string to date from one format and form the new date into the new string format. Something like this:

NSDateFormatter  *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"]; //convert the string into date (american time zone)
    NSDate *theDate = [formatter dateFromString:textdate.text];
    [formatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss ZZZ"];// as @Logan suggested
    NSString *newDate = [formatter stringFromDate:theDate];

Outras dicas

EEE, d MMM yyyy HH:mm:ss ZZZ

Your time zone code was lowercase instead of uppercase.

zzz corresponds to PDT

ZZZ corresponds to -0500

UTS 35

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top