Monday, July 29, 2013

iOS- NSString to NSDate and NSDate to NSString

Here is the code snippet to show NSString convert to NSDate and NSDate convert to NSString


Input Date string and date formate
for example [aa dateFromString:@"your date" and @"dd/MM/yyyy hh:mm"];

+(NSDate*)dateFromString: (NSString*)dateString and: (NSString*)format
{
    
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];

    // Server sends Sydney time
    NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"Australia/Sydney"];
    [dateformatter setTimeZone:zone];

    // set locale, we use us date time style,
   // if you want to force to display 12 hour style or 24 hour style, you can set  en_US_POSIX force to     use 12 hour style
    NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    
    // date string to NSdate
    [dateformatter setLocale:locale];
    [dateformatter setDateFormat:format];
    NSDate *date =[dateformatter dateFromString:dateString];

    return  date;
}

+(NSString*)stringFromDate: (NSDate*)date and: (NSString*)format
{

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:format];
     NSTimeZone *zone = [NSTimeZone localTimeZone];
    [dateFormat setTimeZone:zone];
    
    NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    
    [dateFormat setLocale:locale];
    
     return [dateFormat stringFromDate:date];

}

No comments:

Post a Comment