[ACCEPTED]-UIDatePicker to show year only-ios

Accepted answer
Score: 15

I have a little code that I was about to 6 delete, but the snippet is better off if 5 it is online somewhere. It's not amazing, but 4 it is searchable!

Objective-C code to create an array of all years since 1960. Perfect for input into 3 a UIPicker

//Get Current Year into i2
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init]autorelease];
[formatter setDateFormat:@"yyyy"];
int i2  = [[formatter stringFromDate:[NSDate date]] intValue];


//Create Years Array from 1960 to This year
years = [[NSMutableArray alloc] init];
for (int i=1960; i<=i2; i++) {
    [years addObject:[NSString stringWithFormat:@"%d",i]];
}

The UIPickerView data source and delegate methods:

- (NSInteger)numberOfComponentsInPickerView: (UIPickerView*)thePickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component
{
    return [years count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView
titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [years objectAtIndex:row];
}

Don't 2 forget the declaration in the interface

//Data
NSMutableArray *years;

The 1 out put of it is

enter image description here

Referenced from here

Score: 5

You can't do this with UIDatePicker, but you can with 3 UIPicker.

You need to create an array for the years, and 2 add them to the UIPicker using the UIPicker delegates

Here's 1 a tutorial.

Score: 3

I cannot comment, but I was playing around 10 with the answer by Wolvorin and I decided 9 to do a way where the most recent year would 8 be at the top of the Picker. Currently, his 7 code goes oldest to most recent years.

All 6 I changes was in my NSMutableArray setup 5 in the viewDidLoad instead of his:

//Create Years Array from 1960 to This year
years = [[NSMutableArray alloc] init];
for (int i=1960; i<=i2; i++) {
    [years addObject:[NSString stringWithFormat:@"%d",i]];
}

I used:

years = [[NSMutableArray alloc] init];
for (int i1=i2; i1<=i2 & i1>=1920; i1--) {
    [years addObject:[NSString stringWithFormat:@"%d",i1]];
}

Which 4 does the for in reversed order going from 3 the most recent date, then subtracting one 2 year (and adding it to the Array) until 1 it gets to 1920.

My formula:

int i1=i2; i1<=i2 & i1>=1920; i1--
Score: 3

Just updating the existing answer in this 1 post with Swift 3:

var yearsTillNow : [String] {
    var years = [String]()
    for i in (1970..<2018).reversed() {
        years.append("\(i)")
    }
    return years
}

Just use this for your UIPickerView datasource.

Score: 3

It is not possible to set only Year and 24 Month. Only these modes are available as 23 of iOS 13.5.1

  • time: A mode that displays 22 the date in hours, minutes, and (optionally) an 21 AM/PM designation. The exact items shown 20 and their order depend upon the locale set. An 19 example of this mode is [ 6 | 53 | PM ].

  • date: A 18 mode that displays the date in months, days 17 of the month, and years. The exact order 16 of these items depends on the locale setting. An 15 example of this mode is [ November | 15 14 | 2007 ].

  • dateAndTime: A mode that displays 13 the date as unified day of the week, month, and 12 day of the month values, plus hours, minutes, and (optionally) an 11 AM/PM designation. The exact order and format 10 of these items depends on the locale set. An 9 example of this mode is [ Wed Nov 15 | 6 8 | 53 | PM ].

  • countDownTimer: A mode that 7 displays hour and minute values, for example 6 [ 1 | 53 ]. The application must set a timer 5 to fire at the proper interval and set the 4 date picker as the seconds tick down. UIDatePicker.Mode - developer.apple.com


You 3 may build it using a custom UIPickerView.

class DatePickerViewController: UIViewController {
    var dates =  [Date]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        
        
        var date = Date().addYear(n: -10)
        let endDate = Date().addYear(n: 10)
        
        repeat {
            date = date.addMonth(n: 1)
            dates.append(date)
        } while date < endDate
        
        
        let picker = UIPickerView()
        picker.dataSource = self
        picker.delegate = self
        picker.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(picker)
        
        picker.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        picker.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        picker.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        picker.heightAnchor.constraint(equalToConstant: 500).isActive = true
    }
}


extension  DatePickerViewController: UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.dates.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        let date = self.dates[row]
        return date.stringDate()
    }
    
    func view(forRow row: Int, forComponent component: Int) -> UIView? {
        let label =  UILabel()
        return label
    }
}

extension  DatePickerViewController: UIPickerViewDelegate {
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let date = self.dates[row]
        // Date that the user select. 
        print( date, date.stringDate())
    }
}


extension Date {
    public  func addYear(n: Int) -> Date {
        let calendar = Calendar.current
        return calendar.date(byAdding: .year, value: n, to: self)!
    }
    
    public  func addMonth(n: Int) -> Date {
        let calendar = Calendar.current
        return calendar.date(byAdding: .month, value: n, to: self)!
    }
    
    public  func stringDate() -> String {
        let calendar  = Calendar.current
        let dateFormatter = DateFormatter()
        
        dateFormatter.timeZone = calendar.timeZone
        dateFormatter.locale = calendar.locale
        // Use YYYY to show year only. 
        // Use MMMM to show month only. 
        dateFormatter.setLocalizedDateFormatFromTemplate("MMMM YYYY")
        
        let dateString = dateFormatter.string(from: self)
        return dateString
    }
}

Just 2 change the following two lines- add/subtract 1 as many years you wish to show.

var date = Date().addYear(n: -10) 
let endDate = Date().addYear(n: 10)

Score: 0

I changed Sharukh Mastan's code slightly 4 to always show the current year on top.

var formattedDate: String? = ""

let format = DateFormatter()
format.dateFormat = "yyyy"
formattedDate = format.string(from: date)

var yearsTillNow: [String] {
    var years = [String]()
    for i in (Int(formattedDate!)!-70..<Int(formattedDate!)!+1).reversed() {
        years.append("\(i)")
    }
    return years
}

print(yearsTillNow)

This 3 prints an array of years going back for 2 70 years which you can use as UIPickerView 1 datasource

More Related questions