如何在 Swift 中将字符串转换为 NSDate?

How to convert string to NSDate in Swift?

如何将 05/18/2017 这样的字符串转换为 NSDate

我正在尝试将此字符串转换为 NSDate,以便我可以将日期提取为 18,将月份提取为 05,年份为 2017。我如何转换它或从字符串中提取这些值。

func toDate(dateString : String, dateFormat : String = "yyyy-MM-dd'T'HH:mm:ssX")-> NSDate!{
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateFormat = dateFormat
  dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
  dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
  let convertedDate = dateFormatter.dateFromString(dateString)
  return convertedDate
}

现在在下面的代码中 selectedValue05/18/2017NSDateFromString 总是显示零值:

let nsdateFromString = String.toDate(selectedValue)

遇到这种情况我该怎么办?

您的函数 toDate 的默认 dateFormat 值与 selectedValue 的日期格式不匹配,因此您还需要在方法调用中传递 dateFormat 参数值为 MM/dd/yyyy.

let nsdateFromString = String.toDate(dateString: selectedValue, dateFormat: "MM/dd/yyyy")
func convertSToD(date : String)-> Date?{
        if date != "NA"{
        let interval = Double(date)
        let dateFormat = Date(timeIntervalSince1970: interval!)
        return dateFormat
        }
        return nil
    }

试试这个:-

func toDate(dateString : String, dateFormat : String = "MM/dd/yyyy")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
**in SWIFT 3.0,**


let strDate = "12/21/2017"
let datefrmter = DateFormatter()
datefrmter.dateFormat = "mm/dd/yyyy"
let date = datefrmter.date(from: strDate)
print(date)

转换当前日期和时间

let formatter1 = DateFormatter()

        let date1 = Date.init()
        formatter1.dateFormat = "dd-MMM-yyyy hh:mm a"
        let days = formatter1.string(from: date1 as Date)

        print(days)
//in Swift 3.0 converting string to NSDate with its format
let dateString = self.scoring_date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
dateFormatter.locale = Locale.init(identifier: "en_GB")

self.dateObj = dateFormatter.date(from: dateString! as String )!

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: self.dateObj))")

//converting NSDate to String
let today = Date()
today.toString(dateFormat: "dd-MM")