Ans
Ans

Reputation: 3571

Convert (Date + Time) from NSString to NSDate and Add Some Hours

Requirement is very simple. I have a date+time in 2014-05-16 09:10am format. I want to convert it in NSDate so that I can add/remove few hours to get a time span for some calculation. What exactly dateFormat should I use while converting this NSString value into NSDate ? I have tried following

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm a"];
[dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm a"];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm"];
[dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm a"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm ZZZZ"];

I searched on SO but couldn't get the exact answer. I tried mentioned solutions too by molding them according to my requirement but no gain so far. So I'm posting my query here.

Upvotes: 0

Views: 628

Answers (2)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

 NSString* dateString = "2014-05-16 09:10am";
NSDateFormatter* formt = [NSDateFormatter new];
[formt setDateFormat:"yyyy-MM-dd  hh:mma"];   //hh - for 12 hours format
NSDate* date = [formt dateFromString:dateString];

 NSLog(@"your date is ==%@",date);

if u need to add some hours

NSTimeInterval  InEightHours = 8 * 60 * 60;  //mutiple the hours with minutes
NSDate *dateHoursAhead = [date dateByAddingTimeInterval:InEightHours];

NSLog(@"your final date is ==%@", dateHoursAhead);

Upvotes: 1

Kumar KL
Kumar KL

Reputation: 15335

The problem is with your Hours HH - 24 hours format && hh - 12 hours format .

According to your input date String, This is working fine

 NSString* strdate = @"2014-05-16 09:10am";

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mma"];
    NSDate *date = [dateFormatter dateFromString:strdate];

Upvotes: 1

Related Questions