Date string to NSDate swift

陌路散爱 提交于 2019-11-28 12:25:57

问题


i'm having an array fill with date string, which i would like to go through and check whether the date is today or yesterday. The date string could look like following:

2015-04-10 22:07:00

So far i've tried just to convert it using dateFormatter, but it keeps returning nil

    var dateString = arrayNews[0][0].date as NSString
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

    var date = dateFormatter.dateFromString(dateString as String)
    println(date)

the sudo code i would like to look something like this

if dateString == currentDate
    date = "Today, hh:mm"
else if dateString == currentDate(-1)
    date = "Yesterday, hh:mm
else
    date = dd. MM, hh:mm

in the else statement the date could be 1. April, 12:00

How can i achieve such a logic?

Without the logic

func getDate(dateStr:String, format:String = "yyyy-MM-dd HH:mm:ss") -> NSString {
    var dateFmt = NSDateFormatter()
    dateFmt.timeZone = NSTimeZone.defaultTimeZone()
    dateFmt.dateFormat = format
    let newsDate = dateFmt.dateFromString(dateStr)!

    let date = NSDate();
    let dateFormatter = NSDateFormatter()


    dateFormatter.timeZone = NSTimeZone()
    let localDate = dateFormatter.stringFromDate(date)


    return ""
}

回答1:


You have to use yyyy-MM-dd HH:mm:ss instead of yyyy-MM-dd hh:mm:ss

  • HH: 24h format
  • hh: 12h format (with AM/PM)

Pay attention with dateFormatter, by default, it use localtime zone. println() shows the value for GMT time, which is hold by NSDate.

It means, without specifying timezone, when you convert your string 2015-04-10 22:07:00 to NSDatetime, it return a data which is the time at your local time zone is 2015-04-10 22:07:00. As NSDate holds date time in GMT, you will see a different value when you show the value of that NSDate with println().

If your timezone is GMT+2 (2h earlier than GMT), when it's 22h:07 in your place, the GMT time is 20h:07. When you call println() on that NSDate, you see 2015-04-10 20:07:00

To compare 2 NSDate:

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)

let compareResult = calendar?.compareDate(date, toDate: date2, toUnitGranularity: NSCalendarUnit.CalendarUnitDay)

if (compareResult == NSComparisonResult.OrderedSame) {
    println("yes")
} else {
    println("no")
}

//to get yesterday, using NSCalendar:

let yesterday = calendar?.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -1, toDate: date, options: NSCalendarOptions.MatchStrictly)


来源:https://stackoverflow.com/questions/29650490/date-string-to-nsdate-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!