How to format a date using different formats in Swift

1 Answer

0 votes
import Foundation

// Current date/time
let now: Date = Date()

// Helper to format using a pattern
func fmt(_ pattern: String) -> String {
    let df = DateFormatter()
    df.locale = Locale(identifier: "en_US_POSIX")
    df.dateFormat = pattern
    return df.string(from: now)
}

print("Original Date: \(now)\n")

// --- BASIC COMPONENTS ---

print("Year (4 digits): \(fmt("yyyy"))")      
print("Year (2 digits): \(fmt("yy"))")       

print("Month (01-12): \(fmt("MM"))")          
print("Month name (short): \(fmt("MMM"))")    
print("Month name (full): \(fmt("MMMM"))")    

print("Day of month: \(fmt("dd"))")           
print("Day of week (short): \(fmt("E"))")     
print("Day of week (full): \(fmt("EEEE"))")   

// --- COMMON FULL FORMATS ---

print("YYYY-MM-DD: \(fmt("yyyy-MM-dd"))")
print("DD/MM/YYYY: \(fmt("dd/MM/yyyy"))")
print("MM-DD-YYYY: \(fmt("MM-dd-yyyy"))")

print("YYYY/MM/DD HH:MM:SS: \(fmt("yyyy/MM/dd HH:mm:ss"))")

// --- TIME FORMATS ---

print("24-hour time: \(fmt("HH:mm:ss"))")
print("12-hour time: \(fmt("hh:mm:ss a"))")

// --- HUMAN-READABLE TEXT FORMATS ---

print("Full readable date: \(fmt("EEEE, MMMM dd, yyyy"))")
print("Full date + time: \(fmt("EEEE, MMMM dd, yyyy HH:mm:ss"))")

// --- ISO / RFC STANDARDS ---

let iso = ISO8601DateFormatter()
iso.formatOptions = [.withInternetDateTime]
print("ISO 8601: \(iso.string(from: now))")

let rfc = DateFormatter()
rfc.locale = Locale(identifier: "en_US_POSIX")
rfc.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
print("RFC 2822-like: \(rfc.string(from: now))")

// --- CUSTOM WITH TIMEZONE ---

print("With timezone: \(fmt("yyyy-MM-dd HH:mm:ss zzz"))")



/*
run:

Original Date: 2026-05-20 16:40:51 +0000

Year (4 digits): 2026
Year (2 digits): 26
Month (01-12): 05
Month name (short): May
Month name (full): May
Day of month: 20
Day of week (short): Wed
Day of week (full): Wednesday
YYYY-MM-DD: 2026-05-20
DD/MM/YYYY: 20/05/2026
MM-DD-YYYY: 05-20-2026
YYYY/MM/DD HH:MM:SS: 2026/05/20 16:40:51
24-hour time: 16:40:51
12-hour time: 04:40:51 PM
Full readable date: Wednesday, May 20, 2026
Full date + time: Wednesday, May 20, 2026 16:40:51
ISO 8601: 2026-05-20T16:40:51Z
RFC 2822-like: Wed, 20 May 2026 16:40:51 +0000
With timezone: 2026-05-20 16:40:51 UTC

*/

 



answered May 20 by avibootz
...