Friday, May 10, 2013

NSDateFormatter setDateFormat example ios


setDateFormat:

Sets the date format for the receiver.
- (void)setDateFormat:(NSString *)string
Parameters
string
The date format for the receiver. See Data Formatting Guide for a list of the conversion specifiers permitted in date format strings.


Example of [NSDateFormatter setDateFormat]
NSDate *data = [NSDate stringWithFormat:@"%@", [date text]];];
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MMdd hh:mm"];

NSDate *dateFromString = [dateFormatter dateFromString:data];
NSLog(@"%@", dateFromString);
Example of [NSDateFormatter setDateFormat]
NSString *date = [NSString stringWithFormat:@"11230530"];
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MMddHHmm"];

NSDate *dateFromString = [dateFormatter dateFromString:date];
NSLog(@"%@", dateFromString);
[dateFormatter release];

dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd MMMM' at 'hhmm a"];
NSString *stringFromDate=[dateFormatter stringFromDate:dateFromString];
//Use this text to display in that textfield
[dateFormatter release];
Example of [NSDateFormatter setDateFormat]
+ (NSDateFormatter *) dateFormatterMonthDayOnly {
    NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *format = [dateFormatter dateFormat];
    format = [format stringByReplacingOccurrencesOfString:@"/yy" withString:@""];
    NSRange range;
    range.location = 0;
    range.length = 3;
    format = [format substringWithRange:range];
    [dateFormatter setDateFormat:format];
    return dateFormatter;
}
Example of [NSDateFormatter setDateFormat]
+ (NSDateFormatter *)dateFormatterWithoutYear {
  NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
  [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  NSString *format = [dateFormatter dateFormat];
  format = [format stringByReplacingOccurrencesOfString:@"/yy" withString:@""];
  NSRange secondSpace;
  secondSpace.location = format.length-2;
  secondSpace.length = 1;
  format = [format stringByReplacingCharactersInRange:secondSpace withString:@""];
  [dateFormatter setDateFormat:format];
  return dateFormatter;
}