如何获取当前日期?

22

如何获取当前日期并将其格式化为“20/12/2010”?

3个回答

41

使用NSDateNSDateFormatter

NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSString *dateString = [dateFormat stringFromDate:today];
NSLog(@"date: %@", dateString);

另请参见。


能否将“dd”替换为“周一”,“周二”等等的形式? - Supertecnoboff
@Supertecnoboff - 你可以使用的所有内容都在苹果文档中提到了。例如:http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns - martin clayton

6

分解它。

如何获取当前日期?请查看NSDate

如何按特定格式格式化日期?请查看NSDateFormatter


2

以下是在IOS 9上使用Swift检索当前日期并将其打印为字符串的方法:

    let formatter : NSDateFormatter = NSDateFormatter()
    formatter.dateFormat = "d/M/yy"
    let myStr : String = formatter.string(from:   NSDate.init(timeIntervalSinceNow: 0) as Date)
    print(myStr)

XCode 调试输出

5/6/16

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接