66 lines
2.1 KiB
Swift
66 lines
2.1 KiB
Swift
// ── Format Utilities ───────────────────────────────────────────
|
|
// Ported from web/src/lib/format.ts
|
|
|
|
import Foundation
|
|
|
|
// MARK: - Duration Formatting
|
|
|
|
/// Format seconds as HH:MM:SS or MM:SS
|
|
func formatDuration(_ seconds: TimeInterval) -> String {
|
|
guard seconds > 0 else { return "00:00" }
|
|
let totalSeconds = Int(seconds)
|
|
let hours = totalSeconds / 3600
|
|
let minutes = (totalSeconds % 3600) / 60
|
|
let secs = totalSeconds % 60
|
|
|
|
if hours > 0 {
|
|
return String(format: "%02d:%02d:%02d", hours, minutes, secs)
|
|
}
|
|
return String(format: "%02d:%02d", minutes, secs)
|
|
}
|
|
|
|
/// Format seconds as compact string: "2h 15m", "45m", "30s"
|
|
func formatDurationCompact(_ seconds: TimeInterval) -> String {
|
|
guard seconds > 0 else { return "0s" }
|
|
let totalSeconds = Int(seconds)
|
|
let hours = totalSeconds / 3600
|
|
let minutes = (totalSeconds % 3600) / 60
|
|
let secs = totalSeconds % 60
|
|
|
|
if hours > 0 && minutes > 0 { return "\(hours)h \(minutes)m" }
|
|
if hours > 0 { return "\(hours)h" }
|
|
if minutes > 0 && secs > 0 && minutes < 5 { return "\(minutes)m \(secs)s" }
|
|
if minutes > 0 { return "\(minutes)m" }
|
|
return "\(secs)s"
|
|
}
|
|
|
|
/// Format a date as relative time: "in 5m", "2h ago", "now"
|
|
func formatRelativeTime(_ targetTime: Date, now: Date = Date()) -> String {
|
|
let diff = targetTime.timeIntervalSince(now)
|
|
let absDiff = abs(diff)
|
|
|
|
if absDiff < 30 { return "now" }
|
|
|
|
let compact = formatDurationCompact(absDiff)
|
|
return diff > 0 ? "in \(compact)" : "\(compact) ago"
|
|
}
|
|
|
|
/// Format time as "10:42 AM"
|
|
func formatTime(_ date: Date) -> String {
|
|
let formatter = DateFormatter()
|
|
formatter.dateFormat = "h:mm a"
|
|
return formatter.string(from: date)
|
|
}
|
|
|
|
/// Format date as "Mon, Feb 27"
|
|
func formatDate(_ date: Date) -> String {
|
|
let formatter = DateFormatter()
|
|
formatter.dateFormat = "EEE, MMM d"
|
|
return formatter.string(from: date)
|
|
}
|
|
|
|
/// Format full date-time as "Mon, Feb 27 at 10:42 AM"
|
|
func formatDateTime(_ date: Date) -> String {
|
|
"\(formatDate(date)) at \(formatTime(date))"
|
|
}
|