我学得很快,并且对将日期String转换为NSDate转换为string感到震惊。我正在以以下格式获取日期字符串:“ 2015年10月22日星期四07:45:17 +0000”。我需要以MM-dd-yyyy格式显示日期。我尝试了以下代码,但返回“ null”。
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
let dateObj = dateFormatter.dateFromString(dateString!)
print("Dateobj: \(dateObj)")
谁能帮忙哪里出错了?期待帮助。提前致谢。
首先,您需要使用其格式将字符串转换为NSDate。然后,将更dateFormatter
改为简单格式,然后将其转换回字符串。
迅捷3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
打印结果为: Dateobj: 10-22-2015
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
Swift 2 and below
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
And in Swift 3 and higher this would now be written as:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")
本文地址:http://ios.askforanswer.com/ruhezaiswift-ioszhongjiangzifuchuanriqizhuanhuanweizifuchuanzhongfu.html
文章标签:ios , nsdate , nsdateformatter , string , swift
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
文章标签:ios , nsdate , nsdateformatter , string , swift
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!