在 iOS Swift 中将 NSDate 转换为字符串 [英] Convert NSDate to String in iOS Swift
本文介绍了在 iOS Swift 中将 NSDate 转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将 NSDate
转换为 String
,然后更改格式.但是当我将 NSDate
传递给 String
时,它会产生空格.
let formatter = DateFormatter()让 myString = (String(描述:日期))formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"让你的日期:日期?= formatter.date(来自:myString)formatter.dateFormat = "dd-MMM-yyyy"打印(你的日期)
解决方案
您可以从
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)
解决方案
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)
you get the output as
这篇关于在 iOS Swift 中将 NSDate 转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文