我如何转换,NSDate到NSString,以便只有年在@“yyyy”格式输出到字符串?
当前回答
如果你没有NSDate -descriptionWithCalendarFormat:timeZone:locale: available(我不相信iPhone/Cocoa Touch包括这个),你可能需要使用strftime和一些c风格的字符串。您可以使用NSDate -timeIntervalSince1970从NSDate中获取UNIX时间戳。
其他回答
swift格式:
func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: calndarIdentifier)
formatter.dateFormat = dateFormat
return formatter
}
//Usage
let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018
迅速回答
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)
}
如何……
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
//unless ARC is active
[formatter release];
Swift 4.2:
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:@"yyyy"]; // Date formater
NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
NSLog(@"date :%@",date);
网络上有很多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 ;-)
推荐文章
- 如何使用@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是否支持文档生成?