Wednesday, 13 March 2013

Just Change your date from current format to another ...



I create this method for convert some string date format to convert in another format...

Call bellow method with its 3 parameters..


1. stringDate : Pass your date which in string type.
2. dateFormat : set format which is use in your passed string date. For ex if your string date is "14-03-2013 11:22 am" then set format @"dd-MM-yyyy hh:mm a".
3. getwithFormat : Set format which you want like if you want date "14/03/2013" then just set format @"dd/MM/yyyy".

How to call this see bellow example with method..

NSString *strSDate = [self changeDateFormat:@"14-03-2013 11:22 am" dateFormat:@"dd-MM-yyyy hh:mm a" getwithFormat:@"dd/MM/yyyy"];

Output is : 14/03/2013


-(NSString *)changeDateFormat:(NSString*)stringDate dateFormat:(NSString*)dateFormat getwithFormat:(NSString *)getwithFormat{
    
    
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:dateFormat];
    
    NSDate *date = [dateFormatter dateFromString:stringDate];
    
    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:getwithFormat];
    
    NSString *convertedString = [dateFormatter stringFromDate:date];
    NSLog(@"Converted String : %@",convertedString);
    return convertedString;
}


Also Get Date in NSDate from NSString with my bellow custom Method...

-(NSDate *)convertStringToDate:(NSString *) date dateFormat:(NSString*)dateFormat{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    NSDate *nowDate = [[[NSDate alloc] init] autorelease];
    [formatter setDateFormat:dateFormat];// set format here which format in string date
    date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
    nowDate = [formatter dateFromString:date];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
    return nowDate;

}

and use it like bellow...

NSDate *startDate = [self convertStringToDate:@"2013-05-27 19:00" dateFormate:@"yyyy-MM-dd HH:mm"];
NSDate *endDate = [self convertStringToDate:@"2013-05-27 20:00" dateFormate:@"yyyy-MM-dd HH:mm"];

No comments:

Post a Comment