Skip to content
DeveloperMemos

Getting the Current Year with Swift

Swift, iOS Development, Date and Time1 min read

When developing iOS applications with Swift, it is often necessary to work with dates and retrieve specific components like the current year. In this article, we will explore various approaches to obtain the current year using Swift. We will cover both basic and more advanced methods, allowing you to choose the one that best suits your needs.

Using the Date Class

One straightforward way to get the current year in Swift is by utilizing the Date class. The Date class represents a specific point in time and provides several methods for working with dates and times.

To obtain the current year, you can use the Calendar class along with the component(_:from:) method:

1let currentDate = Date()
2let calendar = Calendar.current
3let currentYear = calendar.component(.year, from: currentDate)
4print("The current year is \(currentYear)")

In the above code, we create an instance of Date representing the current date and time. Then, we access the default calendar using Calendar.current. Finally, we extract the year component from the current date using the component(_:from:) method.

Using DateFormatter

Another approach to retrieve the current year involves using the DateFormatter class. This class provides methods for formatting and parsing dates, making it useful in various scenarios.

To get the current year using DateFormatter, you can format the current date as a string and extract the year component:

1let dateFormatter = DateFormatter()
2dateFormatter.dateFormat = "yyyy"
3let currentYearString = dateFormatter.string(from: Date())
4if let currentYear = Int(currentYearString) {
5 print("The current year is \(currentYear)")
6}

In this example, we create an instance of DateFormatter and set the desired date format using the dateFormat property. By specifying "yyyy" as the format, we ensure that only the year component is included in the resulting string. We then convert the formatted string to an integer to obtain the current year.

Using Calendar Components

Swift provides a convenient way to retrieve specific components of a date directly using the Calendar struct's static method current.component(_:from:). This approach allows you to obtain the current year without explicitly creating a Date instance:

1let calendar = Calendar.current
2if let currentYear = calendar.dateComponents([.year], from: Date()).year {
3 print("The current year is \(currentYear)")
4}

In this code snippet, we access the default calendar using Calendar.current. By calling dateComponents(_:from:) with .year, we extract only the year component from the current date and store it in the currentYear variable.