ios 如何快速将日期格式从 dd/MM/YYYY 转换为 YYYY-MM-dd

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38503489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:44:42  来源:igfitidea点击:

How to convert date format from dd/MM/YYYY to YYYY-MM-dd in swift

iosswiftnsdateformatter

提问by iParesh

I tired to covert from 21/07/2016to 2016-07-21but got this date 2015-12-20
Here is the Code that i have try

我厌倦了从21/07/2016到 2 016-07-21但得到了这个日期2015-12-20
这是我尝试过的代码

let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/YYYY"

let outputFormatter = NSDateFormatter()
outputFormatter.dateFormat = "YYYY-MM-dd"

let showDate = inputFormatter.dateFromString("07/21/2016")
let resultString = outputFormatter.stringFromDate(showDate!)

print(resultString)

How to convert?
Thank you

如何转换?
谢谢

回答by Nirav D

First changes your yearformatter with yyyyand instead of using two NSDateFormatteruse just one like this

首先改变你的year格式化程序yyyy而不是使用两个NSDateFormatter像这样使用一个

let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/yyyy"
let showDate = inputFormatter.dateFromString("07/21/2016")
inputFormatter.dateFormat = "yyyy-MM-dd"
let resultString = inputFormatter.stringFromDate(showDate!)
print(resultString)

For swift3

对于 swift3

func convertDateFormater(_ date: String) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
        let date = dateFormatter.date(from: date)
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return  dateFormatter.string(from: date!)

    }

回答by ahmedomer

You can define a function like the one below:

你可以定义一个像下面这样的函数:

// input string should always be in format "21/07/2016" ("dd/MM/yyyy")

func formattedDateFromString(dateString: String, withFormat format: String) -> String? {

    let inputFormatter = NSDateFormatter()
    inputFormatter.dateFormat = "dd/MM/yyyy"

    if let date = inputFormatter.dateFromString(dateString) {

      let outputFormatter = NSDateFormatter()
      outputFormatter.dateFormat = format

      return outputFormatter.stringFromDate(date)
    }

    return nil
}

You can use the above to pass an output format for your date string. Input format will always be dd/MM/yyyy. Then you use it as follows:

您可以使用上述内容为日期字符串传递输出格式。输入格式将始终为 dd/MM/yyyy。然后按如下方式使用它:

let stringA = formattedDateFromString("21/07/2016", withFormat: "yyyy-MM-dd")
let stringB = formattedDateFromString("21/07/2016", withFormat: "MMM dd, yyyy")

NSLog("stringA: \(stringA)") // 2016-07-21
NSLog("stringB: \(stringB)") // Jul 21, 2016