Home > other >  SWIFT 5 compare date to know if is DAY or NIGHT
SWIFT 5 compare date to know if is DAY or NIGHT

Time:06-24

I created a function that lets you know if the current time is day or night. The problem is that even after sunset, the app tells me it's still daytime. So I think the IF conditions are not correct. Can you help me find the solution? The app uses the user's exact sunset and sunrise time. You have to compare them with the present time. thank you

func actualTime(sunrise: Date, sunset: Date) {
    let date = Date()
    if (date < sunrise && date > sunset) {
        let nightTime = GrowingNotificationBanner(
            title: "Fuel Reserve AI: NIGHT-TIME".localised(),
            subtitle: "PlaneCalc applies nighttime fuel regulations".localised(),
            style: .warning
            
        )
        hapticWarning()
        nightTime.show()
    }
    else {
        let dayTime = GrowingNotificationBanner(
            title: "Fuel Reserve AI: DAY-TIME".localised(),
            subtitle: "PlaneCalc applies daytime fuel regulations".localised(),
            style: .success
        )
        dayTime.show()
    }
}

CodePudding user response:

Your if condition fails because of midnight, before midnight a time after sunset is not before sunrise for instance. So you need to include midnight in your comparisons

Check if now is between midnight and sunrise or after sunset to identify nighttime, otherwise it is daytime

func actualTime(sunrise: Date, sunset: Date) {
    let date = Date()
    let previousMidnight = Calendar.current.startOfDay(for: date)
    if date >= previousMidnight && date < sunrise ||
        date > sunset {
        print("It's night")
    }
    else {
        print("It's day")
    }
}
  • Related