First and Last Day of the Current Month in Swift

first and last day of the current month in swift

You get the first day of the month simply with

let components = calendar.components([.Year, .Month], fromDate: date)
let startOfMonth = calendar.dateFromComponents(components)!
print(dateFormatter.stringFromDate(startOfMonth)) // 2015-11-01

To get the last day of the month, add one month and subtract one day:

let comps2 = NSDateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = calendar.dateByAddingComponents(comps2, toDate: startOfMonth, options: [])!
print(dateFormatter.stringFromDate(endOfMonth)) // 2015-11-30

Alternatively, use the rangeOfUnit method which gives you
the start and the length of the month:

var startOfMonth : NSDate?
var lengthOfMonth : NSTimeInterval = 0
calendar.rangeOfUnit(.Month, startDate: &startOfMonth, interval: &lengthOfMonth, forDate: date)

For a date on the last day of month, add the length of the month minus one second:

let endOfMonth = startOfMonth!.dateByAddingTimeInterval(lengthOfMonth - 1)

Updated for Swift5:

extension Date {
var startOfDay: Date {
return Calendar.current.startOfDay(for: self)
}

var startOfMonth: Date {

let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.year, .month], from: self)

return calendar.date(from: components)!
}

var endOfDay: Date {
var components = DateComponents()
components.day = 1
components.second = -1
return Calendar.current.date(byAdding: components, to: startOfDay)!
}

var endOfMonth: Date {
var components = DateComponents()
components.month = 1
components.second = -1
return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth)!
}

func isMonday() -> Bool {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: self)
return components.weekday == 2
}
}

How to get start date and end date of the current month (Swift 3)

You should write this simple code:

let dateFormatter = DateFormatter()
let date = Date()
dateFormatter.dateFormat = "dd-MM-yyyy"

For start Date:

let comp: DateComponents = Calendar.current.dateComponents([.year, .month], from: date)
let startOfMonth = Calendar.current.date(from: comp)!
print(dateFormatter.string(from: startOfMonth))

For end Date:

var comps2 = DateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = Calendar.current.date(byAdding: comps2, to: startOfMonth)
print(dateFormatter.string(from: endOfMonth!))

How to get start date and end date of previous month in Swift

first you get current month by current date
then minus 1 to get previous month

extension Date {

func addingRmoving(months: Int) -> Date? {
let calendar = Calendar(identifier: .gregorian)

var components = DateComponents()
components.calendar = calendar
components.timeZone = TimeZone(secondsFromGMT: 0)
components.month = months

return calendar.date(byAdding: components, to: self)
}


var startOfMonth: Date {

let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.year, .month], from: self)

return calendar.date(from: components)!
}


var endOfMonth: Date {
var components = DateComponents()
components.month = 1
components.second = -1
return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth)!
}



}

and how to use it

let lastMonth = Date().addingRmoving(months: -1)
let fisrtDayOfLastMonth = lastMonth.startOfMonth
let lastDayOfLastMonth = lastMonth.endOfMonth

Get the first day of all weeks of current month in iOS swift

You can create a DateComponents with the components:

year: someYear,
month: someMonth,
weekday: someCalendar.firstWeekday,
weekOfMonth: n

use Calendar.date(from:) to get the Date corresponding to those components. Now you just need to vary n from 1 to 5, and put each result into an array.

var firstsOfWeek = [Date]()
let year = 2020
let month = 10
let calendar = Calendar.current

for n in 1...5 {
let dc = DateComponents(
year: year,
month: month,
weekday: calendar.firstWeekday,
weekOfMonth: n
)
firstsOfWeek.append(calendar.date(from: dc)!)
}

However, date(from:) will return a date that is not in someMonth if the first week of someMonth is only partially inside someMonth. For example, (assuming the week starts on a Sunday) the first week of October 2020 starts on 27 September, and date(from:) will give you that date if you ask it what the date corresponding to weekOfMonth: 1 is.

If you don't want that date. simply add a check to only include the start of month if it is a start of week as well, and change the for loop range to 2...5:

let firstDayOfMonth = calendar.date(from: DateComponents(year: year, month: month))!
if calendar.component(.weekday, from: firstDayOfMonth) == calendar.firstWeekday {
firstsOfWeek.append(firstDayOfMonth)
}
for n in 2...5 {
...

But do note that if you do this, the resulting array will sometimes have 4 elements, and sometimes 5 elements.

How to get the last date of the month

There are many ways, here are two of them:

Get next 1. and subtract one day

func lastDayOfMonth1() -> Date
{
let calendar = Calendar.current
let components = DateComponents(day:1)
let startOfNextMonth = calendar.nextDate(after:Date(), matching: components, matchingPolicy: .nextTime)!
return calendar.date(byAdding:.day, value: -1, to: startOfNextMonth)!
}

print(lastDayOfMonth1())

Use range(of:in:for:) to get the last day from the range and set the components accordingly:

func lastDayOfMonth2() -> Date
{
let calendar = Calendar.current
let now = Date()
var components = calendar.dateComponents([.year, .month, .day], from: now)
let range = calendar.range(of: .day, in: .month, for: now)!
components.day = range.upperBound - 1
return calendar.date(from: components)!
}

print(lastDayOfMonth2())

Get the first day of a month in swift

Well to get the corresponding number of the day of the week you can use:

var weekday = calendar!.component(NSCalendarUnit.Weekday, fromDate: yourNSDate)
var weekdayName = self.getDayOfWeek(weekday)

Then you can call this function I created to get the corresponding name of the day of the week based on the number passed in to getDayOfWeek()

func getDayOfWeek(weekday:Int) -> String {
if(weekday == 1) {
return "Sunday"
}
else if(weekday == 2) {
return "Monday"
}
else if(weekday == 3) {
return "Tuesday"
}
else if(weekday == 4) {
return "Wednesday"
}
else if(weekday == 5) {
return "Thursday"
}
else if(weekday == 6) {
return "Friday"
}
else {
return "Saturday"
}

}

And if you are using a String as a date to begin with you can change it into an NSDate like this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /*place date format here*/
let date = dateFormatter.dateFromString(/*your_date_string*/)

How to get previous and next month in calendar-Swift

Try like this.

To get date of next month.

Swift 3 and Swift 4

let nextMonth = Calendar.current.date(byAdding: .month, value: 1, to: Date())

Swift 2.3 or lower

let nextMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: NSDate(), options: [])

To get date of previous month.

Swift 3

let previousMonth = Calendar.current.date(byAdding: .month, value: -1, to: Date())

Swift 2.3 or lower

let previousMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: NSDate(), options: [])

Note: To get date of next and previous month I have used todays date, you can use date from which you want next and previous month date, just change NSDate() with your NSDate object.

Edit: For continues traveling of next and previous months you need to store one date object currentDate and when you try to get next and previous month use that date object and update it.

For next month.

let currentDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: currentDate, options: [])

For previous month.

let currentDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: currentDate, options: [])

You can also use extension that will make thing easy.

Swift 3

extension Date {
func getNextMonth() -> Date? {
return Calendar.current.date(byAdding: .month, value: 1, to: self)
}

func getPreviousMonth() -> Date? {
return Calendar.current.date(byAdding: .month, value: -1, to: self)
}
}

Swift 2.3 or lower

extension NSDate {
func getNextMonth() -> NSDate?{
return NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: self, options: [])
}

func getPreviousMonth() -> NSDate?{
return NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: self, options: [])
}
}

Now just get date from currentDate.

currentDate = currentDate.getNextMonth()
currentDate = currentDate.getPreviousMonth()


Related Topics



Leave a reply



Submit