NSDate与NSDateFormatter的相关用法

时间:2023-02-10 23:17:45

NSDate与NSDateFormatter的相关用法

 

1.NSDateFormatter配合NSDate与NSString之间的转化
  NSDateFormatter有下面2个方法:
  - (NSString *)stringFromDate:(NSDate *)date;//NSDate转NSString
  - (NSDate *)dateFromString:(NSString *)string;//NSString转NSDate




列:


    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];

    [dateFormattersetDateFormat:@"MM-dd"];

    //String-data

   NSDate *date = [dateFormatter dateFromString:@"06-22"];

    //data-string month

    [dateFormattersetDateFormat:@"M"];

   NSString *monthStr = [[dateFormatter stringFromDate:date] stringByAppendingString:@""];

    //data-string day

    [dateFormattersetDateFormat:@"d"];

   NSString *dayStr = [dateFormatter stringFromDate:date];

    

    //输出格式为:monthday

   NSString* finallyStr=[monthStr stringByAppendingString:dayStr];

注意:MM带0 M不带0

DD带0 D不带0