How to Get Monday'S Date of the Current Week in Swift

How to get Monday 00:00 of current week? Swift 3

Your code returns the first day in the given week, that may be
a Sunday or Monday (or perhaps some other day), depending on your locale.

If you want Monday considered to be the first weekday then set

cal.firstWeekday = 2

If you want the Monday of the given week, independent of what the
start of the week is, then set comps.weekday = 2:

func getMonday(myDate: Date) -> Date {
let cal = Calendar.current
var comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: myDate)
comps.weekday = 2 // Monday
let mondayInWeek = cal.date(from: comps)!
return mondayInWeek
}

Note that printing a Date always uses the GMT time zone,
you'll need a date formatter to print the result according to your local time zone. Example:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm"

let now = Date()
print(df.string(from: now)) // 2016-10-02 20:16

let monday1 = getMonday(myDate: now)
print(df.string(from: monday1)) // 2016-09-26 00:00

How to get Monday's date of the current week in swift

I wrote Date extensions to get Date for certain weekday and here is how easy it is to use with Swift 5,

Date.today()                                  // Oct 15, 2019 at 9:21 AM
Date.today().next(.monday) // Oct 21, 2019 at 9:21 AM
Date.today().next(.sunday) // Oct 20, 2019 at 9:21 AM


Date.today().previous(.sunday) // Oct 13, 2019 at 9:21 AM
Date.today().previous(.monday) // Oct 14, 2019 at 9:21 AM

Date.today().previous(.thursday) // Oct 10, 2019 at 9:21 AM
Date.today().next(.thursday) // Oct 17, 2019 at 9:21 AM
Date.today().previous(.thursday,
considerToday: true) // Oct 10, 2019 at 9:21 AM


Date.today().next(.monday)
.next(.sunday)
.next(.thursday) // Oct 31, 2019 at 9:21 AM

And here is Date extension for that,

extension Date {

static func today() -> Date {
return Date()
}

func next(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.next,
weekday,
considerToday: considerToday)
}

func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.previous,
weekday,
considerToday: considerToday)
}

func get(_ direction: SearchDirection,
_ weekDay: Weekday,
considerToday consider: Bool = false) -> Date {

let dayName = weekDay.rawValue

let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() }

assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")

let searchWeekdayIndex = weekdaysName.firstIndex(of: dayName)! + 1

let calendar = Calendar(identifier: .gregorian)

if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex {
return self
}

var nextDateComponent = calendar.dateComponents([.hour, .minute, .second], from: self)
nextDateComponent.weekday = searchWeekdayIndex

let date = calendar.nextDate(after: self,
matching: nextDateComponent,
matchingPolicy: .nextTime,
direction: direction.calendarSearchDirection)

return date!
}

}

// MARK: Helper methods
extension Date {
func getWeekDaysInEnglish() -> [String] {
var calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale(identifier: "en_US_POSIX")
return calendar.weekdaySymbols
}

enum Weekday: String {
case monday, tuesday, wednesday, thursday, friday, saturday, sunday
}

enum SearchDirection {
case next
case previous

var calendarSearchDirection: Calendar.SearchDirection {
switch self {
case .next:
return .forward
case .previous:
return .backward
}
}
}
}

Get an Array of Dates of the current week starting on Monday

You just need to get the first day of the week using iso8601 calendar where the first weekday is Monday and add from 0 to 6 days to it. Try like this:

extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}
extension Date {
var startOfWeek: Date {
return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
}
var daysOfWeek: [Date] {
let startOfWeek = self.startOfWeek
return (0...6).compactMap{ Calendar.current.date(byAdding: .day, value: $0, to: startOfWeek)}
}
}

Date().daysOfWeek  // ["Aug 13, 2018 at 12:00 AM", "Aug 14, 2018 at 12:00 AM", "Aug 15, 2018 at 12:00 AM", "Aug 16, 2018 at 12:00 AM", "Aug 17, 2018 at 12:00 AM", "Aug 18, 2018 at 12:00 AM", "Aug 19, 2018 at 12:00 AM"]

Get the current week number in month from Date

This is due to the 1st day of the month falling on a sunday, try march 01, 2020 if you want confirmation.

The first week of the month is chosen by Swift according to their own standards as ISO standards do not suggest any specific implementations so the Swift team went with this. You can ask them in their forums what their reasoning behind this is Wikipedia link

How to get all days in current week in swift

To get the weekdays of the week, it is:

let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let days = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
.compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
.filter { !calendar.isDateInWeekend($0) }

To display that as "Thursday = 82", it is

let formatter = DateFormatter()
formatter.dateFormat = "eeee' = 'D"
for date in days {
print(formatter.string(from: date))
}

Or

let strings = days.map { formatter.string(from: $0) }

Current Week Start and End Date

I solve the problem thanks for Support

Code :- it give the current week start and end date.

 NSDate *today = [NSDate date];
NSLog(@"Today date is %@",today);
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format.

//Week Start Date

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];

int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week

[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.

NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:@"yyyy-MM-dd"];
dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];

weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];

NSLog(@"%@",weekstartPrev);


//Week End Date

NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];

int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week

[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week

NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:@"yyyy-MM-dd"];
dateEndPrev = [dateFormat stringFromDate:EndOfWeek];

weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];
NSLog(@"%@",weekEndPrev);

How to make an array of the current week dates Swift

You can get today's yearForWeekOfYear and weekOfYear calendar components and construct a new date from it. It will give you the first day of the week. If you want your week to start from Monday you need to use iso8601 calendar, if you would like to have your week to start on Sunday you can use Gregorian calendar. To avoid some extreme cases you should do all your calendrical calculations using noon time. Not all dates starts at midnight.

let dateComponents = Calendar(identifier: .gregorian).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())
let startOfWeek = Calendar(identifier: .gregorian).date(from: dateComponents)!
let startOfWeekNoon = Calendar(identifier: .gregorian).date(bySettingHour: 12, minute: 0, second: 0, of: startOfWeek)!
let weekDays = (0...6).map { Calendar(identifier: .gregorian).date(byAdding: .day, value: $0, to: startOfWeekNoon)! }
weekDays // ["Jun 7, 2020 at 12:00 PM", "Jun 8, 2020 at 12:00 PM", "Jun 9, 2020 at 12:00 PM", "Jun 10, 2020 at 12:00 PM", "Jun 11, 2020 at 12:00 PM", "Jun 12, 2020 at 12:00 PM", "Jun 13, 2020 at 12:00 PM"]

Expanding on that you can extend Date and create some helpers:

extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
static let gregorian = Calendar(identifier: .gregorian)
}

extension Date {
func byAdding(component: Calendar.Component, value: Int, wrappingComponents: Bool = false, using calendar: Calendar = .current) -> Date? {
calendar.date(byAdding: component, value: value, to: self, wrappingComponents: wrappingComponents)
}
func dateComponents(_ components: Set<Calendar.Component>, using calendar: Calendar = .current) -> DateComponents {
calendar.dateComponents(components, from: self)
}
func startOfWeek(using calendar: Calendar = .current) -> Date {
calendar.date(from: dateComponents([.yearForWeekOfYear, .weekOfYear], using: calendar))!
}
var noon: Date {
Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
func daysOfWeek(using calendar: Calendar = .current) -> [Date] {
let startOfWeek = self.startOfWeek(using: calendar).noon
return (0...6).map { startOfWeek.byAdding(component: .day, value: $0, using: calendar)! }
}
}

usage:

// this will give you all days of the current week starting monday
Date().daysOfWeek(using: .iso8601) // ["Jun 8, 2020 at 12:00 PM", "Jun 9, 2020 at 12:00 PM", "Jun 10, 2020 at 12:00 PM", "Jun 11, 2020 at 12:00 PM", "Jun 12, 2020 at 12:00 PM", "Jun 13, 2020 at 12:00 PM", "Jun 14, 2020 at 12:00 PM"]
// this will give you all days of the current week starting sunday
Date().daysOfWeek(using: .gregorian) // ["Jun 7, 2020 at 12:00 PM", "Jun 8, 2020 at 12:00 PM", "Jun 9, 2020 at 12:00 PM", "Jun 10, 2020 at 12:00 PM", "Jun 11, 2020 at 12:00 PM", "Jun 12, 2020 at 12:00 PM", "Jun 13, 2020 at 12:00 PM"]

To convert your date to a fixed date format you can create a custom date formatter extending Formatter and Date:

extension Formatter {
static let ddMMyyyy: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd.MM.yyyy"
return dateFormatter
}()
}

extension Date {
var ddMMyyyy: String { Formatter.ddMMyyyy.string(from: self) }
}

Now you can simply map your dates using the KeyPath:

Date().daysOfWeek(using: .gregorian).map(\.ddMMyyyy) // ["07.06.2020", "08.06.2020", "09.06.2020", "10.06.2020", "11.06.2020", "12.06.2020", "13.06.2020"]

How to get start and end of the week in swift?

Your code is working perfectly fine. If you would run your code in a Playground, you could see the actual Date objects rather than there String representations. Even if you don't specify a DateFormatter, under the hood, when doing print(Date()), Swift uses a DateFormatter to print Date objects and hence that value will be a relative time instead of the absolute point in time provided by the Date object.

In a Playground you can see that the actual startOfWeek is "Sep 25, 2017 at 12:00 AM", while the endOfWeek is "Oct 1, 2017 at 12:00 AM", which are the correct values for the current week.

Don't use print(Date()) for checking the correctness of Date objects, since as you can see, it will yield unexpected results due to the underlying DateFormatters used.

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

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)

How to find the next weekday or weekend using swift?

Finding the date for the next weekend is simple.

let now = Date()
if let timeInterval = cal.nextWeekend(startingAfter: now, direction: .forward) {
let startDate = timeInterval.start
let endDate = timeInterval.end
print(startDate, endDate)
}

nextWeekend(startingAfter:direction:) does not return a specific Date object. It returns a DateInterval object, instead.

Finding the next date for any of week days is a challenge. That's because it can be Monday, Tuesday, Wednesday, Thursday or Friday. The following is how to find the next Monday.

let cal = Calendar.current
var comps = DateComponents()
comps.weekday = 2
let now = Date()
if let nextMonday = cal.nextDate(after: now, matching: comps, matchingPolicy: .nextTimePreservingSmallerComponents) {
print(nextMonday)
}

, where 2 is for Monday.



Related Topics



Leave a reply



Submit