Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. Date / DateFormatter / Calendar

Date / DateFormatter / Calendar

Swift's Foundation framework provides Date, DateFormatter, and Calendar for working with dates and times — including formatting, parsing, and date arithmetic.

Class overview

Class / PropertyDescription
Date()Creates an object representing the current date and time.
DateFormatterA class that converts between Date values and strings.
DateFormatter.dateFormatSets the format string for the date and time (e.g., yyyy/MM/dd).
DateFormatter.localeSets the locale used for formatting.
CalendarPerforms calendar calculations, retrieves date components, and adds or subtracts date values.
DateComponentsA structure that represents date and time components such as year, month, day, hour, minute, and second.
timeIntervalSince1970Returns the number of seconds elapsed since January 1, 1970 (Unix timestamp).

Sample code

import Foundation

// Get the current date and time
let now = Date()
print("Now: \(now)")

// DateFormatter: convert between Date and String
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
formatter.locale = Locale(identifier: "en_US")

let dateString = formatter.string(from: now)
print("Formatted: \(dateString)")

// Parse a string into a Date
if let parsedDate = formatter.date(from: "2026/03/06 12:00:00") {
    print("Parsed: \(parsedDate)")
}

// Calendar: extract date components
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: now)
print("Year: \(components.year!), Month: \(components.month!), Day: \(components.day!)")

// Calendar: add days to a date
var addComponents = DateComponents()
addComponents.day = 7  // 7 days later

if let nextWeek = calendar.date(byAdding: addComponents, to: now) {
    print("One week later: \(formatter.string(from: nextWeek))")
}

// Compare two dates
let date1 = now
let date2 = calendar.date(byAdding: .hour, value: 3, to: now)!
print("date2 is after date1: \(date2 > date1)")

// Unix timestamp
print("Unix timestamp: \(Int(now.timeIntervalSince1970))")

Notes

Date stores time internally in UTC (Coordinated Universal Time). When displaying a date, use DateFormatter to apply the appropriate locale and time zone.

Creating a DateFormatter is expensive, so avoid instantiating it repeatedly. Reuse it via a static property or lazy var instead. The format string in dateFormat is case-sensitive. 'MM' means month; 'mm' means minute. An incorrect format string may cause the formatter to return nil.

For URL handling, see URL / URLComponents / URLSession.

If you find any errors or copyright issues, please .