简体   繁体   English

字符串到 NSdate 返回 nil

[英]String to NSdate returns nil

I want to separate my String dateTime to different variables date and time because I will display it separately.我想将我的 String dateTime 与不同的变量 date 和 time 分开,因为我将单独显示它。 How could I do this?我怎么能这样做?

Here's my code in getting the date only and it returns nil:这是我仅获取日期的代码,它返回 nil:

let datetime = "2015-04-06T13:24:11.913"
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM-DD-YYYY"
    let date = dateFormatter.dateFromString(datetime)
    println(date)

Thanks in advance.提前致谢。

Update: This is my error,更新:这是我的错误,在此处输入图片说明

Update 2: It doesn't return an error but it gives me the wrong Month for the formatted date更新 2:它不会返回错误,但它为我提供了错误的格式化日期月份

在此处输入图片说明

Use this formatter使用这个格式化程序

let datetime = "2015-04-06T13:24:11.913"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.dateFromString(datetime)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour, fromDate: date!)
components.day//This is 6

Your formatter have to match your string您的格式化程序必须匹配您的字符串

This is my playground screenshot,it works well.这是我的游乐场截图,效果很好。在此处输入图片说明

        let datetime = "2015-04-06T13:24:11" //"2015-04-06T13:24:11.913"
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-mm-dd'T'HH:mm:ss" //"yyyy-mm-dd'T'HH:mm:ss.SSS"
        let date = dateFormatter.dateFromString(datetime)
        let myTime = NSDateFormatter.localizedStringFromDate(date!, dateStyle: .NoStyle , timeStyle: .MediumStyle)
        let myDate = NSDateFormatter.localizedStringFromDate(date!, dateStyle: .ShortStyle , timeStyle: .NoStyle)

        println(date!)//DateWithTime
        println(myDate)//Date
        println(myTime)//time 

This helps you for formatting.. NSDateFormatter_Class这有助于您格式化.. NSDateFormatter_Class在此处输入图片说明 Thanks to @LeonardoSavioDabus for given this image => Swift NSDate UTC time and local time感谢@LeonardoSavioDabus 提供此图像 => Swift NSDate UTC 时间和本地时间

Besides the problem that the string you were testing had milliseconds while the date from your array has only seconds, now the problem is that Y is for week of year.除了您正在测试的字符串有毫秒而数组中的日期只有秒的问题之外,现在的问题是 Y 是一年中的一周。 You need to use lowercase "y" with the date format and also lowercase "d".您需要在日期格式中使用小写的“y”以及小写的“d”。 The date format should look like this:日期格式应如下所示:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

to extract the month component from a date you can use this extension:要从日期中提取月份组件,您可以使用此扩展程序:

extension Date {
    var month: Int {
        Calendar(identifier: .gregorian).component(.month, from: self)
    }
}


NSDate().month   // 5

All of the NSDateFormatter s in other answers will give the wrong date once the user sets the iOS calendar to anything other than the gregorian calendar.一旦用户将 iOS 日历设置为公历以外的任何内容,其他答案中的所有NSDateFormatter都会给出错误的日期。 Your date string doesn't mention any timezone as well so I'm going to assume is UTC.您的日期字符串也没有提到任何时区,所以我假设是 UTC。

let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(name: "UTC")
formatter.calendar = NSCalendar.gregorianCalendar()
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS"

Try like this way,试试这个方法

    let datetime = "2015-04-06T13:24:11.913"
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    let dateFromString = dateFormatter.dateFromString(datetime)
    var calendar = NSCalendar.currentCalendar()
    var components:NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond | NSCalendarUnit.CalendarUnitHour, fromDate: dateFromString!)
    var stringDate = "\(components.month)-\(components.day)-\(components.year)"
    var stringTime = "\(components.hour):\(components.minute):\(components.second)"
    println(stringDate)
    println(stringTime)

You will get output Like :你会得到像这样的输出:

4-6-2015 4-6-2015

13:24:11 13:24:11

Enjoy Coding !!享受编码!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM