How can i get all the months of a year in a table view in this particular format "January 2013" and so on. I need to set the starting month also. Below is the code i tried.
int mCurrentMonth = [dateComponents month];
int mCurrentYear = [dateComponents year];
NSString * dateString = [NSString stringWithFormat: @"%d",mCurrentMonth];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
NSString *mon = [NSString stringWithFormat:@"%@ %d",stringFromDate, mCurrentYear];
NSLog(@"month:%@", mon);
Above code is giving me only current month in required format. Other way i tried is this
NSDateFormatter *df = [[NSDateFormatter alloc] init];
for (int i = 0; i < 12; i++){
NSString *monthName = [[df monthSymbols] objectAtIndex:i];
NSLog(@"months name:%@", monthName);
}
This way i am getting all months name but not with year. I am not getting how to achieve the desired output that is January 2013 February 2013 and so on.
Try this :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *today = [NSDate date];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *yearComponents = [currentCalendar components:NSYearCalendarUnit fromDate:today];
int currentYear = [yearComponents year];
for(int months = 0; months < 12; months++)
NSLog(@"%@ %i",[[dateFormatter monthSymbols]objectAtIndex: months],currentYear);
output will be :
January 2013
February 2013
March 2013
April 2013
May 2013
June 2013
July 2013
August 2013
September 2013
October 2013
November 2013
December 2013
Edited : For Above output from current month Use following code :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *today = [NSDate date];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *yearComponents = [currentCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:today];
int currentYear = [yearComponents year];
int currentmonth=[yearComponents month];
NSLog(@"current Month %d",currentmonth);
for(int months = currentmonth - 1; months < 12; months++)
NSLog(@"%@ %i",[[dateFormatter monthSymbols]objectAtIndex: months],currentYear);
Swift 4.2
let dateFormatter = DateFormatter()
let today = Date()
let currentCalendar = Calendar.current
var yearComponents: DateComponents? = currentCalendar.dateComponents([.year], from: today)
let currentYear = Int(yearComponents!.year!)
for months in 0..<12 {
print("\(dateFormatter.shortMonthSymbols[months]) \(currentYear)")
}
Output:
Jan 2017
Feb 2017
Mar 2017
Apr 2017
May 2017
Jun 2017
Jul 2017
Aug 2017
Sep 2017
Oct 2017
Nov 2017
Dec 2017
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With