我如何转换,NSDate到NSString,以便只有年在@“yyyy”格式输出到字符串?
当前回答
iOS 15更新
iOS 15现在支持直接在Date对象上调用.格式化,而不需要显式的DateFormatter。
常见格式示例
文档
date.formatted() // 6/8/2021, 7:30 PM
date.formatted(date: .omitted, time: .complete) // 19:30
date.formatted(date: .omitted, time: .standard) // 07:30 PM
date.formatted(date: .omitted, time: .shortened) // 7:30 PM
date.formatted(date: .omitted, time: .omitted)
替代语法
文档
// We can also specify each DateComponent separately by chaining modifiers.
date.formatted(.dateTime.weekday(.wide).day().month().hour().minute())
// Tuesday, Jun 8, 7:30 pm
// Answer to specific question
date.formatted(.dateTime.year())
其他回答
我不知道为什么我们都错过了这个:localizedStringFromDate:dateStyle:timeStyle:
NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterFullStyle];
NSLog(@"%@",dateString);
输出'13/06/12 00:22:39 GMT+ 00:00 '
iOS 15更新
iOS 15现在支持直接在Date对象上调用.格式化,而不需要显式的DateFormatter。
常见格式示例
文档
date.formatted() // 6/8/2021, 7:30 PM
date.formatted(date: .omitted, time: .complete) // 19:30
date.formatted(date: .omitted, time: .standard) // 07:30 PM
date.formatted(date: .omitted, time: .shortened) // 7:30 PM
date.formatted(date: .omitted, time: .omitted)
替代语法
文档
// We can also specify each DateComponent separately by chaining modifiers.
date.formatted(.dateTime.weekday(.wide).day().month().hour().minute())
// Tuesday, Jun 8, 7:30 pm
// Answer to specific question
date.formatted(.dateTime.year())
网络上有很多NSDate的助手,我倾向于使用:
https://github.com/billymeltdown/nsdate-helper/
自述摘录如下:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
这将产生以下类型的输出:
‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)
希望通过提供包括年、月、日和时间的正常格式化程序来增加更多的价值。 您可以使用这个格式化程序超过一年
[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
objective - c:
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyy";
NSString *dateString = [formatter stringFromDate:date];
迅速:
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let dateString = formatter.string(from: now)
这是nsdateformatter的一个好网站。您可以在不同的本地使用不同的DateFormatter预览日期字符串。
推荐文章
- NSRange从Swift Range?
- 我可以使用范围操作符与if语句在Swift?
- UICollectionView中的单元格间距
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?
- 在Swift中转换字符串为日期
- 点击按钮时如何打开手机设置?
- 如何使用UIVisualEffectView来模糊图像?
- 如何改变时间和时区在iPhone模拟器?
- 在Swift中使用自定义消息抛出错误/异常的最简单方法?
- 编译器错误:带有Objective-C选择器的方法与前面带有相同Objective-C选择器的声明冲突
- 如何在Swift中获得唯一的设备ID ?
- 如何在Swift中获得枚举值的名称?
- 我如何知道何时UITableView完成了ReloadData?
- 复制文本到剪贴板与iOS
- 如何调用手势点击在UIView编程在迅速