TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: SwiftUI: How to check if date is in the same Year

Forums > SwiftUI

Hie, I have a timestamp such as this one: 2022-01-12T17:06:37.000Z which I obviously want to display in a readable format to the end-user. What I do usually is to check if the date is today, if it is then I take the time from the Timestamp and display it. If it isn't then I display the extract the day and month from the Timestamp and display that. Now the issue is some dates are from last year (2021), so what I want to do is check if the date is from the current year, if it isn't then I want to display the day-month-year. My Current Implementation was built last year before I started dealing with dates from the previous year. BTW: the stringDate parameter comes from a REST API response. Below is my current Implementation:

func DateTimeDisplay(_ stringDate: String) -> some View 
{

    let fromReponseDateformatter = DateFormatter()
    let todayDateformatter = DateFormatter()
    let notTodayDateformatter = DateFormatter()
    let notCurrentYearDateformatter = DateFormatter()

    fromReponseDateformatter.calendar = Calendar(identifier: .iso8601)
    fromReponseDateformatter.locale = Locale(identifier: "en_US_POSIX")
    fromReponseDateformatter.timeZone = TimeZone(secondsFromGMT: 0)
    fromReponseDateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"

    todayDateformatter.dateFormat = "HH':'mm a"

    todayDateformatter.amSymbol = "AM"
    todayDateformatter.pmSymbol = "PM"

    notTodayDateformatter.dateFormat = "dd'/'MM"

    notCurrentYearDateformatter.dateFormat = "dd'/'MM'/'yyyy" // How do I check this part

    let today = fromReponseDateformatter.date(from: stringDate)

    var message = Text("The date received: \(fromReponseDateformatter.string(from: today!))")

    if Calendar.current.isDateInToday(today!)
    {
        message = Text(todayDateformatter.string(from: today!)).font(Font.custom("Poppins-Regular", size: 15))
            .foregroundColor(Color(red: 171/255, green: 171/255, blue: 171/255))
    }
    else
    {

        message = Text(notTodayDateformatter.string(from: today!)).font(Font.custom("Poppins-Regular", size: 15))
            .foregroundColor(Color(red: 171/255, green: 171/255, blue: 171/255))
    }

    return message

}

I got the below extension, but I'm not sure how to use it:

extension Date {

    func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool {
        calendar.isDate(self, equalTo: date, toGranularity: component)
    }

    func isInSameYear(as date: Date) -> Bool { isEqual(to: date, toGranularity: .year) }
    func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) }
    func isInSameWeek(as date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) }

    func isInSameDay(as date: Date) -> Bool { Calendar.current.isDate(self, inSameDayAs: date) }

    var isInThisYear:  Bool { isInSameYear(as: Date()) }
    var isInThisMonth: Bool { isInSameMonth(as: Date()) }
    var isInThisWeek:  Bool { isInSameWeek(as: Date()) }

    var isInYesterday: Bool { Calendar.current.isDateInYesterday(self) }
    var isInToday:     Bool { Calendar.current.isDateInToday(self) }
    var isInTomorrow:  Bool { Calendar.current.isDateInTomorrow(self) }

    var isInTheFuture: Bool { self > Date() }
    var isInThePast:   Bool { self < Date() }
}

3      

If I'm understanding you correctly, this should do what you want:

func dateTimeDisplay(for stringDate: String) -> String {
    let inFormatter = ISO8601DateFormatter()
    inFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    guard let inDate: Date = inFormatter.date(from: stringDate) else {
        fatalError("date cannot be derived from string \"\(stringDate)\"")
    }

    //default to day and month
    var outTemplate = "dd/MM"

    let cal = Calendar.current

    if cal.isDate(inDate, inSameDayAs: .now) {
        outTemplate = "HH:mm a"
    } else if !cal.isDate(inDate, equalTo: .now, toGranularity: .year) {
        outTemplate += "/yyyy"
    }

    let outFormatter = DateFormatter()
    outFormatter.setLocalizedDateFormatFromTemplate(outTemplate)

    return outFormatter.string(from: inDate)
}

//date is today
print(dateTimeDisplay(for: "2022-01-06T17:06:37.000Z"))
//09:06

//date is in same year
print(dateTimeDisplay(for: "2022-01-12T17:06:37.000Z"))
//01/12

//date is in different year
print(dateTimeDisplay(for: "2021-09-10T09:16:57.030Z"))
//09/10/2021

//incorrect date string
print(dateTimeDisplay(for: "2022-01-06T27:06:37.000Z"))
//fatal error!

5      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.