You can find the current year in Swift using the Calendar
and Date
classes like this:
main.swift95 chars4 lines
This code initializes a Calendar
object with the current
calendar and then uses the component(_:from:)
method to get the year
component from the current Date
. The print()
function is then used to output the year
value to the console.
Alternatively, you can use the DateFormatter
class to format the current date as a string that only includes the year:
main.swift140 chars5 lines
This code initializes a DateFormatter
object and sets its dateFormat
property to "yyyy"
, which specifies that only the year should be included in the output string. The string(from:)
method is then used to format the current Date
as a string with the specified format, and the print()
function is used to output the resulting yearString
to the console.
gistlibby LogSnag