Developer
Developer

Reputation: 4321

String to date and to time

Hello i'm having trouble with converting string to date, and date to string with time only. Result is null.

Here is what i am doing:

I have a dictionary, with time in it:

@"Time" : @"2014-07-17T10:38:00+03:00"

I do this:

NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init];
[timeFormat2 setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *date = [timeFormat2 dateFromString:[JSON valueForKey:@"Time"]];

And then this:

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];
NSLog(@"%@",[timeFormat stringFromDate:date]);
cell.iboTimeLabel.text = [timeFormat stringFromDate:date];

And the value is null.

Where is my mistake?

Upvotes: 1

Views: 105

Answers (4)

Bug Hunter Zoro
Bug Hunter Zoro

Reputation: 1915

Set the dateformat to [timeFormat2 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; should do the trick also i suggest reading this document next time you are dealing with such issues.

Upvotes: 1

Darshan Kunjadiya
Darshan Kunjadiya

Reputation: 3329

Try with this format

NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init];
[timeFormat2 setDateFormat:@"yyyy-MM-dd'T'hh:mm:ssZZZZZ"];
NSDate *date = [timeFormat2 dateFromString:@"2014-07-17T10:38:00+03:00"];


NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];
NSLog(@"%@",[timeFormat stringFromDate:date]);

It's working. i hope this is working for you.

Upvotes: 1

Nitin Gohel
Nitin Gohel

Reputation: 49720

You are setting Format of your string date is wrong check with Bellow code:

  NSString *str=@"2014-07-17T10:38:00+03:00";

    NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init];
    [timeFormat2 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate *date = [timeFormat2 dateFromString:str];


    [timeFormat2 setDateFormat:@"HH:mm:ss"];

    NSString *final = [timeFormat2 stringFromDate:date];
    NSLog(@"%@",final);

Upvotes: 3

Ramaraj T
Ramaraj T

Reputation: 5230

Remove the single quotes from the Time string and try. Use the following date formatter.

NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init];
[timeFormat2 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [timeFormat2 dateFromString:@"2014-07-17T10:38:00+03:00"];

Upvotes: 2

Related Questions