Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the first day of current week to Tuesday in Swift?

Tags:

swift3

nsdate

How to set the first day of current week to Tuesday in Swift 3? The schedule will update every Tuesday so the first day have to start from Tuesday.

and then display on label :

thisWeekDate.text! = "\(first day of current week) - \(last day of current week)"

Full code.

let today = NSDate()
    let nextTue = Calendar.current.date(byAdding: .day, value: 6, to: today as Date)
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    let todayString = formatter.string(from: today as Date)
    let nextString = formatter.string(from: nextTue!)
    formatter.dateFormat = "dd-MMM-yyyy"

    let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
    let components = calendar!.components([.weekday], from: today as Date)

    //Label code
    thisWeekDate.text! = "\(first day of current week) - \(last day of current week)"

    //If i can change the first day of current week this weekly update code can be deleted
    if components.weekday == 3 { 
        print("Hello Tuesday")
        thisWeekDate.text! = "\(todayString) - \(nextString)"

        UserDefaults.standard.set(todayString, forKey: "todayStringKey")
        _ = UserDefaults.standard.object(forKey: "todayStringKey") as? String
        UserDefaults.standard.set(nextString, forKey: "nextStringKey")
        _ = UserDefaults.standard.object(forKey: "nextStringKey") as? String

    } else {
        print("It's not Tuesday")
        let RetrivedDate_1 = UserDefaults.standard.object(forKey: "todayStringKey") as? String
        let RetrivedDate_2 = UserDefaults.standard.object(forKey: "nextStringKey") as? String

        if let date_1 = RetrivedDate_1, let date_2 = RetrivedDate_2 {
            thisWeekDate.text! = "\(date_1) - \(date_2)"
        }


    }

App Design Screenshot

App design screenshot

like image 513
Lester Avatar asked Aug 22 '17 06:08

Lester


1 Answers

Create a custom Gregorian calendar and set the first weekday to Tuesday

var customCalendar = Calendar(identifier: .gregorian)
customCalendar.firstWeekday = 3

Then you can get the week interval with

var startDate = Date()
var interval = TimeInterval()
customCalendar.dateInterval(of: .weekOfMonth, start: &startDate, interval: &interval, for: Date())
let endDate = startDate.addingTimeInterval(interval - 1)
print(startDate, endDate)
like image 156
vadian Avatar answered Oct 09 '22 19:10

vadian