Friday, May 10, 2013

NSDateFormatter stringFromDate example ios


stringFromDate:

Returns a string representation of a given date formatted using the receiver’s current settings.
- (NSString *)stringFromDate:(NSDate *)date
Parameters
date
The date to format.
Return Value
A string representation of date formatted using the receiver’s current settings.
Example of [NSDateFormatter stringFromDate]
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];
Example of [NSDateFormatter stringFromDate]
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:@"2010-01-10 13:55:15"];

NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
[f2 setDateFormat:@"d. MMMM YYYY"];
NSString *s = [f2 stringFromDate:date];
Example of [NSDateFormatter stringFromDate]
-(NSString*) Dateformate:(NSString*)str
{    
    NSDateFormatter *dfrt =[[NSDateFormatter alloc] init];
    [dfrt setDateFormat:@"yyyy-MM-dd h:mm:ss"];
    NSDate *presentdate = [dfrt dateFromString:str];
    [dfrt setDateFormat:@"MMMM"];
    NSString *fullMonth = [dfrt stringFromDate:presentdate];

    [dfrt setDateFormat:@"yyyy"];
    NSString *yearStr = [dfrt stringFromDate:presentdate];
   // NSLog(@"month %@",presentdate);

    [dfrt setFormatterBehavior:NSDateFormatterBehavior10_4];
    [dfrt setDateFormat:@"d"];
    int date_day = [[dfrt stringFromDate:presentdate] intValue];
    NSString *suffix_string = @"|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st";
    NSArray *suffixes = [suffix_string componentsSeparatedByString: @"|"];
    NSString *suffix = [suffixes objectAtIndex:date_day];

    NSString *fullDateFormat = [NSString stringWithFormat:@"%@ %d%@ %@",fullMonth,date_day,suffix,yearStr];

   // NSLog(@"fullDateFormat %@",fullDateFormat);

    return fullDateFormat;

}