Bilal Bakhrom
Bilal Bakhrom

Reputation: 166

How to fix calendar issue in swift? (glad to see even in objective-c)

I have used several methods of calendar instance. So, isDateInToday() and isDateInTomorrow() are main methods that have effect to UI part. Let's use isDateInToday() for today (my local time is 28th August, 2019 21:37:00 ), it shows the following:

00:00 - 4:59 (false). Here isDateInTomorrow() shows true

5:00 - 23:59 (true)

Calendar identifier is gregorian

Locale is en_US

timeZone is GMT (secondsFromGMT=0)

That's the calendar instance:

private var _calendar: Calendar = {
        var cal = Calendar.current
        cal.locale = Locale.current
        cal.timeZone = TimeZone(secondsFromGMT: 0)!
        return cal
    }()

That's how I'm creating date:

public var today: Date? {
        let date = Date()

        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        formatter.locale = .current
        let dateString = formatter.string(from: date)

        let formatterOut = DateFormatter()
        formatterOut.dateFormat = "yyyy-MM-dd HH:mm:ss"
        formatterOut.locale = Locale(identifier: "ru")
        formatterOut.timeZone = TimeZone(secondsFromGMT: 0)

        return formatterOut.date(from: dateString)
}

What should I do that it should show true for today between 00:00 and 23:59?

Upvotes: 1

Views: 283

Answers (2)

Murod Mamadjanov
Murod Mamadjanov

Reputation: 15

Try to create date with your local time zone interval:

let seconds: TimeInterval = TimeInterval(TimeZone.current.secondsFromGMT())
let date = Date(timeIntervalSinceNow: seconds)

Upvotes: 1

Bilal Bakhrom
Bilal Bakhrom

Reputation: 166

Well, I have not found exact solution for this. But I have done it. I have created two date instances for today and tomorrow.

...
let today = Date()
...
let tomorrow = calendar.date(byAdding: .day, value: 1, to: today)

And that's my solution for isDateInToday() and isDateInTomorrow(). I have ignored time.

func isDateInToday(_ date: Date) -> Bool {
    let year = calendar.compare(date, to: today, toGranularity: .year)
    let month = calendar.compare(date, to: today, toGranularity: .month)
    let day = calendar.compare(date, to: today, toGranularity: .day)
    return (year == .orderedSame && month == .orderedSame && day == .orderedSame)
}

func isDateInTomorrow(_ date: Date) -> Bool {
    let year = calendar.compare(date, to: tomorrow, toGranularity: .year)
    let month = calendar.compare(date, to: tomorrow, toGranularity: .month)
    let day = calendar.compare(date, to: tomorrow, toGranularity: .day)
    return (year == .orderedSame && month == .orderedSame && day == .orderedSame)
}

Upvotes: 1

Related Questions