How do I find the number of days in given month and year using swift
First create an NSDate
for the given year and month:
let dateComponents = NSDateComponents()
dateComponents.year = 2015
dateComponents.month = 7
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!
Then use the rangeOfUnit()
method, as described in
Number of days in the current month using iPhone SDK?:
// Swift 2:
let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
// Swift 1.2:
let range = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)
let numDays = range.length
print(numDays) // 31
Update for Swift 3 (Xcode 8):
let dateComponents = DateComponents(year: 2015, month: 7)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
print(numDays) // 31
How to calculate the number of days in the current month/year
Here is a method which works for both months and years:
let calendar = NSCalendar.currentCalendar()
let date = NSDate()
// Calculate start and end of the current year (or month with `.Month`):
var startOfInterval : NSDate?
var lengthOfInterval = NSTimeInterval()
calendar.rangeOfUnit(.Year, startDate: &startOfInterval, interval: &lengthOfInterval, forDate: date)
let endOfInterval = startOfInterval!.dateByAddingTimeInterval(lengthOfInterval)
// Compute difference in days:
let days = calendar.components(.Day, fromDate: startOfInterval!, toDate: endOfInterval, options: [])
print(days)
(You may want to add some error checking instead of forcibly unwrapping
optionals.)
Update for Swift 3:
let calendar = Calendar.current
let date = Date()
// Calculate start and end of the current year (or month with `.month`):
let interval = calendar.dateInterval(of: .year, for: date)!
// Compute difference in days:
let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
print(days)
Number of days in the current month using iOS?
You can use the NSDate
and NSCalendar
classes:
NSDate *today = [NSDate date]; //Get a date object for today's date
NSCalendar *c = [NSCalendar currentCalendar];
NSRange days = [c rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:today];
today
is an NSDate
object representing the current date; this can be used to work out the number of days in the current month. An NSCalendar
object is then instantiated, which can be used, in conjunction with the NSDate
for the current date, to return the number of days in the current month using the rangeOfUnit:inUnit:forDate:
function.
days.length
will contain the number of days in the current month.
Here are the links to the docs for NSDate
and NSCalendar
if you want more information.
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
Calculating the number of days between two dates in swift
It has to do with the order that you're creating your variables and comparing them.
The first thing you do is create today
. Then, you create twoWeeksFromNow
, based on a new Date()
that will be slightly further in the future than today
was. On my machine, in a playground, the second date is about 300 microseconds further in the future than the first.
Then, for numDaysWithDate
, you compare twoWeeksFromNow
to another new Date()
, even more slightly in the future. So, your time frame is very slightly less than 2 full weeks, giving you 13 days.
But, for numDaysWithToday
, you compare twoWeeksFromNow
with the original today
, which was created before twoWeeksFromNow
was, making it slightly longer than 2 weeks, giving you 14 days.
If you change the order of the the today
and twoWeeksFromNow
declarations, you can see a different result:
var twoWeeksFromNow: Date = Calendar.current.date(byAdding: .day,
value: 14, to: Date())!
var today = Date()
Now, because today
was created slightly later than the date that twoWeeksFromNow
was created from, both results are 13.
How can we get all the days in selected month
You can get the range of day in the month, and map the range initializing a new date using the year and month components of the date combined with the day from the range. I am using noon time because not every date starts at 12am:
extension Date {
func datesInSameMonth(using calendar: Calendar = .current) -> [Date] {
let year = calendar.component(.year, from: self)
let month = calendar.component(.month, from: self)
return calendar.range(of: .day, in: .month, for: self)?.compactMap {
DateComponents(calendar: calendar, year: year, month: month, day: $0, hour: 12).date
} ?? []
}
}
print(Date().datesInSameMonth()) // [2020-09-01 15:00:00 +0000, 2020-09-02 15:00:00 +0000, 2020-09-03 15:00:00 +0000, 2020-09-04 15:00:00 +0000, 2020-09-05 15:00:00 +0000, 2020-09-06 15:00:00 +0000, 2020-09-07 15:00:00 +0000, 2020-09-08 15:00:00 +0000, 2020-09-09 15:00:00 +0000, 2020-09-10 15:00:00 +0000, 2020-09-11 15:00:00 +0000, 2020-09-12 15:00:00 +0000, 2020-09-13 15:00:00 +0000, 2020-09-14 15:00:00 +0000, 2020-09-15 15:00:00 +0000, 2020-09-16 15:00:00 +0000, 2020-09-17 15:00:00 +0000, 2020-09-18 15:00:00 +0000, 2020-09-19 15:00:00 +0000, 2020-09-20 15:00:00 +0000, 2020-09-21 15:00:00 +0000, 2020-09-22 15:00:00 +0000, 2020-09-23 15:00:00 +0000, 2020-09-24 15:00:00 +0000, 2020-09-25 15:00:00 +0000, 2020-09-26 15:00:00 +0000, 2020-09-27 15:00:00 +0000, 2020-09-28 15:00:00 +0000, 2020-09-29 15:00:00 +0000, 2020-09-30 15:00:00 +0000]
Related Topics
Swap Rootviewcontroller With Animation
Swift 5: What's 'Escaping Closure Captures Mutating 'Self' Parameter' and How to Fix It
Finish Asynchronous Task in Firebase With Swift
Cllocationcoordinate2D Can't Be Instantiated
Dismiss Keyboard with a Uitextview
In Swift, How to Convert a String to an Enum
Convert Avaudiopcmbuffer to Nsdata and Back
Downloading and Caching Images from Url Asynchronously
Iboutlet of Another View Controller Is Nil
How to Make Window Transparent in Osx Swift
Generating Random Numbers With Swift
Use Reserved Keyword a Enum Case
Xcode 7.3.1 Hangs on "Copying Swift Standard Libraries"
Swift 2 to 3 Migration for Prepareforsegue
Find Difference in Seconds Between Nsdates as Integer Using Swift
How to Find the Number of Days in Given Month and Year Using Swift