在iOS Swift中将NSDate转换为字符串 [英] Convert NSDate to String in iOS Swift
本文介绍了在iOS Swift中将NSDate转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将NSDate
转换为String
,然后更改格式.但是,当我将NSDate
传递给String
时,它会产生空白.
I am trying to convert a NSDate
to a String
and then Change Format. But when I pass NSDate
to String
it is producing whitespace.
let formatter = DateFormatter()
let myString = (String(describing: date))
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate)
推荐答案
您可以从获取详细信息Apple Dateformatter文档.如果要为dateString设置dateformat,请参阅此链接(详细日期格式)您可以此处 例如,喜欢
you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like
let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date()) // string purpose I add here
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)
print(myStringafd)
您得到的输出为
这篇关于在iOS Swift中将NSDate转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文