Number of Days in the Current Month Using iOS

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.

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)

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 get the current day number in current month and year

let dayYear = Calendar.current.ordinality(of: .day, in: .year, for: Date())

let dayMonth = Calendar.current.ordinality(of: .day, in: .month, for: 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

Number of days in month returns wrong value after 10:00 PM

It's a GMT offset issue combined with the current day in a month.

When you create a date without set a day, it will be set to the first day of the month.

So, if your timezone offset is for example -4 means your are 4 hours behind the GMT 0 and by default the timezone defined at Calendar.current is equal the system timezone. So what it means? Means you'll obtain the previous month if you test it in a boundary of 23 + (-4) or the next month if your offset is positive.

You can test this behaviour copying'n paste the following code in the Playground.

func getDaysInMonth(month: Int, year: Int, offset: Int = 0) -> Int? {
let someDate = DateComponents(year: year, month: month, hour: 3)
var current = Calendar.current
let timezone = TimeZone(secondsFromGMT: 60 * 60 * offset)!
current.timeZone = timezone
guard let someDay = current.date(from: someDate) else { return nil }
print("date: \(someDay)") // this will always
return someDay.daysInCurrentMonth
}

for hour in -12...12 {
print("hour: \(hour)\ndays: \(getDaysInMonth(month: 10, year: 2021, offset: hour) ?? -1)")
print("---\n")
}

extension Date {
var daysInCurrentMonth: Int? {
Calendar.current.range(of: .day, in: .month, for: self)?.count
}
}

Notice the days will change starting by your current system time zone (notice only the month will change).

How to fix this?

In your case, I guess you just want to show how many days a month have, so you can just set the to zero like this:

TimeZone(secondsFromGMT: 0)

Do this change at a instance of Calendar.current and check if it works for you.

How do I calculate the number of days in this year in Objective C

I finally came up with a solution that works. What I do is first calculate the number of months in the year and then for each month calculate the number of days for that month.

The code looks like this:

NSUInteger days = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:today];
NSUInteger months = [calendar rangeOfUnit:NSMonthCalendarUnit
inUnit:NSYearCalendarUnit
forDate:today].length;
for (int i = 1; i <= months; i++) {
components.month = i;
NSDate *month = [calendar dateFromComponents:components];
days += [calendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:month].length;
}

return days;

It is not as neat as I would have hoped for but it will work for any calendar such as the ordinary gregorian one or the islamic one.

Getting the number of days of the month in NSDate in Objective-C?

Try this simple way:

NSCalendar *cal = [NSCalendar currentCalendar];
NSRange rng = [cal rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth = rng.length;

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
}
}

Any way to find number of days in month using Objective C?

You can use NSCalendar and its rangeOfUnit:inUnit:forDate method. For example, to get the number of days in the current month:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth = range.length;


Related Topics



Leave a reply



Submit