Peter Pik
Peter Pik

Reputation: 11193

Date string to NSDate swift

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 ""
}

Upvotes: 0

Views: 3339

Answers (1)

Duyen-Hoa
Duyen-Hoa

Reputation: 15804

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)

Upvotes: 4

Related Questions