Swift根据时间戳显示时间或日期

Mat*_*son 1 nsdate nsdateformatter nscalendar swift

我有一个返回数据的API,包括该记录的时间戳.在swift中我加载了timestamp元素并将其转换为double,然后可以将其转换为时间.如果记录的日期是今天,我希望能够返回时间,如果记录不是今天,我希望返回日期.见下文:

        let unixTimeString:Double = Double(rowData["Timestamp"] as! String)!
        let date = NSDate(timeIntervalSince1970: unixTimeString) // This is on EST time and has not yet been localised.
        var dateFormatter = NSDateFormatter()
        dateFormatter.timeStyle = .ShortStyle
        dateFormatter.doesRelativeDateFormatting = true
        // If the date is today then just display the time, if the date is not today display the date and change the text color to grey.
        var stringTimestampResponse = dateFormatter.stringFromDate(date)
        cell.timestampLabel.text = String(stringTimestampResponse)
Run Code Online (Sandbox Code Playgroud)

我是否使用NSCalendar查看"日期"是否为今天然后做某事?那么你如何本地化时间以使其对用户而不是服务器时间更正?

Abi*_*ern 6

NSCalendar上有一个方便的功能,告诉你NSDate是否在今天(至少需要iOS 8) isDateInToday()

要看它工作,把它放到一个操场上:

// Create a couple of unix dates.
let timeIntervalToday: NSTimeInterval = NSDate().timeIntervalSince1970
let timeIntervalLastYear: NSTimeInterval = 1438435830


// This is just to show what the dates are.
let now = NSDate(timeIntervalSince1970: timeIntervalToday)
let then = NSDate(timeIntervalSince1970: timeIntervalLastYear)

// This is the function to show a formatted date from the timestamp
func displayTimestamp(ts: Double) -> String {
    let date = NSDate(timeIntervalSince1970: ts)
    let formatter = NSDateFormatter()
    formatter.timeZone = NSTimeZone.systemTimeZone()

    if NSCalendar.currentCalendar().isDateInToday(date) {
        formatter.dateStyle = .NoStyle
        formatter.timeStyle = .ShortStyle
    } else {
        formatter.dateStyle = .ShortStyle
        formatter.timeStyle = .NoStyle
    }

    return formatter.stringFromDate(date)
}

// This should just show the time.
displayTimestamp(timeIntervalToday)

// This should just show the date.
displayTimestamp(timeIntervalLastYear)
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想在不自行运行的情况下查看它的外观:

在此输入图像描述