You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中时间戳转日期后如何实现动态自定义格式显示求助

Dynamic Date Formatting for Swift

No problem at all—let's get this dynamic date display sorted out for you! The core idea is to check whether the server date falls on today, yesterday, or an earlier date, then apply the corresponding format. Here's a robust, safe way to implement this:

Step-by-Step Implementation

First, we'll fix optional handling (to avoid crashes from nil values) and add date comparison logic using Calendar—this is far more reliable than manually checking date components since it accounts for time zones and user calendar settings.

// Safely unwrap and convert the timestamp from your JSON response
guard let addedTimeString = dictMessage?.object(forKey: "added_time") as? String,
      let timeInterval = TimeInterval(addedTimeString) else {
    // Handle invalid/missing timestamp case (e.g., show placeholder text)
    cellDetailsShop.lblTimeShop?.text = "N/A"
    return
}

let dateFromServer = Date(timeIntervalSince1970: timeInterval)
let dateFormatter = DateFormatter()
let calendar = Calendar.current

// Determine which format to use based on the date
if calendar.isDateInToday(dateFromServer) {
    dateFormatter.dateFormat = "Today hh:mm a" // Shows "Today 04:55 PM"
} else if calendar.isDateInYesterday(dateFromServer) {
    dateFormatter.dateFormat = "Yesterday h:mm a" // Shows "Yesterday 5 PM" (no leading zero for hours)
} else {
    dateFormatter.dateFormat = "dd-MMM-yyyy hh:mm a" // Original format for older dates
}

// Critical: Set the time zone to match your server's timestamp timezone
// If your server uses UTC, uncomment this line:
// dateFormatter.timeZone = TimeZone(identifier: "UTC")
// Or use the device's local time zone:
dateFormatter.timeZone = TimeZone.current

// Update the label text
cellDetailsShop.lblTimeShop?.text = dateFormatter.string(from: dateFromServer)

Key Notes

  • Safe Unwrapping: The guard let block ensures we don't crash if the timestamp is missing or invalid—always handle these edge cases!
  • Calendar Methods: isDateInToday and isDateInYesterday are built-in methods that handle all the heavy lifting of comparing dates, including time zones and daylight saving time changes.
  • Format Adjustments: Using h instead of hh for yesterday's time removes the leading zero (so "5 PM" instead of "05 PM"), which matches your desired output.
  • Time Zone: Don't forget to set the date formatter's time zone to match what your server uses. If your server returns timestamps in UTC, set dateFormatter.timeZone = TimeZone(identifier: "UTC") to avoid incorrect date comparisons due to local time offsets.

内容的提问来源于stack exchange,提问作者Dilip Tiwari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:38:45