A collection of time conversion methods in ios development
- 2020-05-07 20:30:33
- OfStack
When developing an iOS program, we sometimes need to adjust the time format to the format we want, which we can do with the NSDateFormatter class.
Such as:
// instantiate 1 NSDateFormatter object
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// set the time format, here you can set the format you need
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// get the current system time with [NSDate date]
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
// the output format is: 2010-10-27 10:22:13
NSLog(@"%@",currentDateStr);
// after alloc don't forget release for objects that are not used
[dateFormatter release];
ios method code that converts a timestamp to a time string class
// will date The timestamp is converted to a time string
//@paaram date Time for conversion
//@param formatString Time format (yyyy-MM-dd HH:mm:ss)
//@return NSString Returns a word character such as ( 2012 - 8 - 8 11:11:11 )
+ (NSString *)getDateStringWithDate:(NSDate *)date
DateFormat:(NSString *)formatString
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:formatString];
NSString *dateString = [dateFormat stringFromDate:date];
NSLog(@"date: %@", dateString);
[dateFormat release];
return dateString;
}
The above is all the content of this article, I hope you can enjoy it.