views:

100

answers:

2

Hello Everyone!!

Need Your help.

I have an issue with date Formatter.

I have Two string. one string contains date in form of MM/dd/yyyy; and second string contains time in form of hh:mm a.

Now i want to concatenate this two strings and want output as a new strings in form of yyyy-MM-dd HH:mm:ss.

I have tried following but unfortunately it doesn't work more.

-(NSString *)ConcateDateAndTime:(NSString *)date Time:(NSString *)time{

    date = [date stringByAppendingFormat:@" %@",time];



    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"MM/dd/yyyy hh:mm aa"];

    NSDate *dt = [NSDate date];
    dt = [formater dateFromString:date];

    NSDateFormatter *formater1 = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *temp;
    temp = [formater1 stringFromDate:dt];

    return temp;

}

Kindly guide me to solve this issue.

Looking forwards.

Thank You,

Arun Thakkar.

+2  A: 

Change the second [formater setDateFormat] call to use formater1.

paul_sns
I can't believe I set up a whole project to figure this out and as soon as the debugger gets there, I come back and you've answered. +1
David Kanarek
+1, Also note that this method leaks two date formatters!
Carl Norum
Right on David, I also had to create a Window based project (since it's the one I'm most familiar with) just to try it out. :) Thanks Carl and David for pointing out the memory leak issue.
paul_sns
@David Thanks for the help and sorry for the trouble.
Arun Thakkar
Thanks Paul David and Carl, i will also take care of leaks.
Arun Thakkar
+1  A: 

Use this instead as you've also got a memory leak:

-(NSString *)ConcateDateAndTime:(NSString *)date Time:(NSString *)time{

    date = [date stringByAppendingFormat:@" %@",time];

    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"MM/dd/yyyy hh:mm aa"];

    NSDate *dt = [formater dateFromString:date];

    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    return [formater stringFromDate:dt];

}
David Kanarek