Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách hiển thị ngày giờ hiện tại trong ứng dụng iOS

Xử lý ngày giờ (Date/Time) là kỹ năng cơ bản quan trọng trong phát triển mobile (weather, gaming, scheduling...).

Cách 1: Date() - Ngày giờ hiện tại (UTC)


override func viewDidLoad() {
    super.viewDidLoad()
    
    let currentDate = Date() // Struct Date (Swift native), bridge từ NSDate
    print("UTC: \(currentDate)") // 2024-01-15 08:30:00 +0000
}

Cách 2: DateFormatter - Format theo locale/timezone


let date = Date()
let formatter = DateFormatter()

// Cấu hình
formatter.dateStyle = .full      // "Thứ Hai, 15 tháng 1 năm 2024"
formatter.timeStyle = .short     // "08:30"
formatter.locale = Locale(identifier: "vi_VN") // Tiếng Việt
formatter.timeZone = TimeZone.current        // Múi giờ thiết bị

let formatted = formatter.string(from: date)
print("Localized: \(formatted)") // "Thứ Hai, 15 tháng 1 năm 2024 lúc 08:30"

Cách 3: Custom format pattern


let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // 2024-01-15 08:30:00
formatter.locale = Locale(identifier: "en_US_POSIX") // Quan trọng cho fixed format
formatter.timeZone = TimeZone.current

print(formatter.string(from: Date()))

Cách 4: ISO8601 / RFC3339 (API standard)


let iso8601Formatter = ISO8601DateFormatter()
iso8601Formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let isoString = iso8601Formatter.string(from: Date())
print("ISO8601: \(isoString)") // 2024-01-15T08:30:00.123Z

Cách 5: Relative Date Formatter (iOS 13+)


let relativeFormatter = RelativeDateTimeFormatter()
relativeFormatter.locale = Locale(identifier: "vi_VN")
relativeFormatter.unitsStyle = .full

print(relativeFormatter.localizedString(for: Date(), relativeTo: Date().addingTimeInterval(-3600)))
// "1 giờ trước"

print(relativeFormatter.localizedString(for: Date().addingTimeInterval(86400), relativeTo: Date()))
// "1 ngày tới"

Cách 6: DateComponents - Tạo date từ thành phần


var components = DateComponents()
components.year = 2024
components.month = 12
components.day = 25
components.hour = 10
components.minute = 30
components.timeZone = TimeZone(identifier: "Asia/Ho_Chi_Minh")

let calendar = Calendar.current
if let christmas = calendar.date(from: components) {
    print("Giáng sinh: \(christmas)")
}

Hiển thị trên UILabel (Storyboard)


@IBOutlet weak var dateTimeLabel: UILabel!
var timer: Timer?

override func viewDidLoad() {
    super.viewDidLoad()
    updateDateTimeLabel()
    // Cập nhật mỗi giây
    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
        self.updateDateTimeLabel()
    }
}

func updateDateTimeLabel() {
    let formatter = DateFormatter()
    formatter.dateFormat = "EEEE, dd/MM/yyyy HH:mm:ss"
    formatter.locale = Locale(identifier: "vi_VN")
    dateTimeLabel.text = formatter.string(from: Date())
}

deinit { timer?.invalidate() }

Cách hiển thị ngày giờ hiện tại trong ứng dụng iOS

Best Practices

  • Luôn set locale = Locale(identifier: "en_US_POSIX") cho fixed format (tránh bug 12h/24h)
  • Tái sử dụng DateFormatter (tạo một lần, dùng nhiều lần) - nó tốn tài nguyên
  • Dùng Calendar.current cho phép tính toán ngày (add/subtract days)
  • Timezone: TimeZone.current (device) vs TimeZone(identifier: "UTC") (server)

Swift 5.7+ / iOS 16+: Date.FormatStyle (Modern)


// Cách mới, type-safe, localized by default
let formatted = Date().formatted(
    .dateTime
        .day(.twoDigits)
        .month(.twoDigits)
        .year(.defaultDigits)
        .hour(.twoDigits(amPM: .omitted))
        .minute(.twoDigits)
        .locale(Locale(identifier: "vi_VN"))
)
print(formatted) // "15/01/2024, 08:30"