我如何转换,NSDate到NSString,以便只有年在@“yyyy”格式输出到字符串?
当前回答
迅速回答
static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
let date = dateFormatter.date(from: strDate)
return date!
}
public static func dateToString(inputdate : Date) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
return formatter.string(from: inputdate)
}
其他回答
迅速回答
static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
let date = dateFormatter.date(from: strDate)
return date!
}
public static func dateToString(inputdate : Date) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
return formatter.string(from: inputdate)
}
网络上有很多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 ;-)
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())
如果你在Mac OS X上,你可以这样写:
NSString* s = [[NSDate date] descriptionWithCalendarFormat:@"%Y_%m_%d_%H_%M_%S" timeZone:nil locale:nil];
但是这在iOS上是不可用的。
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:@"yyyy"]; // Date formater
NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
NSLog(@"date :%@",date);
推荐文章
- 如何使用@Binding变量实现自定义初始化
- Swift设置为Array
- 如何设置回退按钮文本在Swift
- 我如何能在Swift扩展类型化数组?
- Swift类错误:属性未在super处初始化。init调用
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- Swift to Objective-C头未在Xcode 6中创建
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 不区分大小写的比较
- 在Swift中将字典转换为JSON
- 我如何模仿地图应用程序的底部表格?
- 改变导航栏后退按钮的颜色
- 编译警告:对于架构i386,没有处理文件的规则
- Swift是否支持文档生成?