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

时间:2017-05-18 09:38:17

标签: ios swift nsdate

如何将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
}

现在,selectedValue下方的代码为05/18/2017,但NSDateFromString始终显示为零值:

let nsdateFromString = String.toDate(selectedValue)

在这种情况下我该怎么办?

6 个答案:

答案 0 :(得分:4)

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

let nsdateFromString = String.toDate(dateString: selectedValue, dateFormat: "MM/dd/yyyy")

答案 1 :(得分:4)

**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)

答案 2 :(得分:0)

func convertSToD(date : String)-> Date?{
        if date != "NA"{
        let interval = Double(date)
        let dateFormat = Date(timeIntervalSince1970: interval!)
        return dateFormat
        }
        return nil
    }

答案 3 :(得分:0)

试试这个: -

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
}

答案 4 :(得分:0)

转换当前日期和时间

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)

答案 5 :(得分:0)

CoreSpider.py