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()
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
How to show previous, current and future months in JTAppleCalendar in Swift
You must return your real startDate instead of Date()
and then scroll to current month.
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy MM dd"
let startDate = formatter.date(from: "2010 01 01")!
let endDate = formatter.date(from: "2050 01 01")!
return ConfigurationParameters(startDate: startDate, endDate: endDate)
}
then in your viewDidLoad
you should call:
collectionView.scrollToDate(Date())
Get the Previous Month days count
These is the usage :
let calendar = Calendar.current
let date1 = calendar.date(byAdding: .month, value: -1, to: Date())! // -1 mean previous month
let range = calendar.range(of: .day, in: .month, for: date1)!
let numDays = range.count
print(numDays)
OUTPUT :
31
How to get the date of previous month matching specified day ? [Swift]
You can use date components as following:
func getPreviousMonthDate(matchingDay day: Int) -> Date {
let calendar = Calendar.current
let comps = calendar.dateComponents([.year, .month, .day], from: Date())
var comps2 = DateComponents()
comps2.year = comps.year
comps2.month = comps.month! - 1
comps2.day = day
return calendar.date(from: comps2)!
}
I force-unwrapped the date to match your function declaration, I suggest that you deal with the optional dates properly though.
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 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 Date by supplying a month and year
You can use DateComponents initializer to compose a new date just passing the month and year components. Just make sure to pass a calendar as well otherwise the result would be nil. Maybe something like:
extension Date {
static func startOfMonth(for month: Int, of year: Int, using calendar: Calendar = .current) -> Date? {
DateComponents(calendar: calendar, year: year, month: month).date
}
}
Date.startOfMonth(for: 2, of: 2021) // "Feb 1, 2021 at 12:00 AM"
Related Topics
Info.Plist Utility Error: "Info.Plist Couldn't Be Opened Because There Is No Such File"
How to Receive Push Notifications of an Other App
How to Animate an Svg Path in iOS
Dragging Scnnode in Arkit Using Scenekit
Uitableviewcell Height Resize When Image Is Downloaded
How to Set the Tab Order in iOS
Presenting Uialertcontroller from Uitableviewcell
Move Gmsmarker on Google Map Like Uber
What Is Main Thread Checker in Xcode
How to Import Existing Objective C Classes in Swift
How to Use Uiviewcontrolleranimatedtransitioning with Uinavigationcontroller
Objective-C Check If Subviews of Rotated Uiviews Intersect
How to Use the Default iOS7 Uianimation Curve
Unknown Class in Interface Builder