uidatepicker 24hour formate in ios - ios

I am Trying to assign the 24 hour formate to UIDATEPICKERVIEW but i have not exactly idea to implement it.
in my view.h file
#property(nonatomic,retain) IBOutlet UIDatePicker *picker_alarm;
in my view.m file
picker_alarm.date=[NSDate date];
in my .xib file
i have taken uidatepicker and its Mode Property to Time in viewcontroller.

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"NL"];
[picker_alarm setLocale:locale];

You can also use the storyboard to change time format to 24 hour.
Follow these steps:
go to storyboard
select you datePicker
select attributes inspector
Change "Locale" property to English(Europe)
and in your code use following snippet:
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"HH:mm"];
somelabel.text = [outputFormatter stringFromDate:_pickerDate.date];

You cannot force the date picker to show 24 hours time. That depends on the locale property
Doc says:
UIDatePickerModeTime, // Displays hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. 6 | 53 | PM)
[datePicker setLocale:[NSLocale systemLocale]];
For testing this change the system time to 24hour mode. And check the picker in simulator

Create DatePicker with setting it custom Locale
let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.time
datePicker.locale = Locale.init(identifier: "NL") //or: Locale.init(identifier:en_GB") // using Great Britain
Grab the time from above DatePicker,
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
lblTime.text = dateFormatter.string(from: sender.date)

Related

UIDatePicker: While selecting date, it jumps to any random date

I have been trying to fix this issue since so long but did not find any way to sort this out.
When I'm trying to select a year sometimes the year component of the date picker jumps to a random year. (The same thing happens with date and month selection)
The data picker is contained in a UIView and I have created an IBOutlet for it.
- (void)setupforBirthdates {
[self.dtPicker setDatePickerMode: UIDatePickerModeDate];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDate *currentDate = [NSDate date];
NSDateComponents * comps = [[NSDateComponents alloc] init];
[comps setYear: -17];
NSDate * maxDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: NSCalendarMatchStrictly];
[comps setYear: -50];
NSDate * minDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: NSCalendarMatchStrictly];
[self.dtPicker setMinimumDate:minDate];
[self.dtPicker setMaximumDate:maxDate];
[self.dtPicker setDate:maxDate];
}
ISSUE See the below image...
I thought that it may be due to some 3rd party libraries this is happening. I have the following pod in my project
pod 'AFNetworking'
pod 'GoogleMaps'
pod 'GooglePlaces'
pod 'Fabric'
pod 'Crashlytics'
pod 'RACollectionViewReorderableTripletLayout'
pod 'FBSDKLoginKit'
pod 'Socket.IO-Client-Swift', '~> 13.3.0'
How can I solve this issue?
Any help/suggestions?
UPDATE
I what to restrict user to select birth year from 17 to 50 year only so the minDate will be 17 years back from current year
maxDate will be 50 years back from the current year
The issue is also coming if I don't set minDate and maxDate
Tested the following case too
I just drag and drop new date picker on screen. I did not set any min/max date, nor connect an IBOutlet and I run app and when I scroll to any date the same issue is coming
You will be surprised that I have created a custom date picker using UIPickerView and the issue is still there.
When I have created a new demo project and copy pasted the code in demo project then this issue is not coming. I've tested it many times on demo project the issue is not coming.
The following func. is called when I change the date in date picker.
- (IBAction)datePickerValueChanged:(id)sender {
NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
self.txtBirthday.text = [NSString stringWithFormat:#"%#",[dateFormat stringFromDate:self.dtPicker.date]];
}
The strange thing is that for the When I just put(drag & drop) UIDatePicker View on a screen just to test its scrolling issue. When I scroll date time picker view then also it was scrolling at random location.
I feel that it is the issue with third party library.
After many hours of debugging and trail-run, I finally found the third party library which was the source of this issue.
Actually is was the category name is UITableView+SPXRevealAdditions.
When I removed it UIDatePicker is working fine and when I re-added the issue is started occurring.
It is really very strange but It worked for me.:D
Update:
I wanted the that 3rd party too. So what I did id added a dummy pan gesture in viewDidLoadMethod:.
UIPanGestureRecognizer *p = [[UIPanGestureRecognizer alloc] initWithTarget:nil action:#selector(doNothing)];
[self.dtPicker addGestureRecognizer:p];
and the dummy method.
- (void)doNothing {
printf("do nothing");
}
This solved my problem and Now the UIDatePicker is working fine and also third party library too...cheers...:D.
You can check whenever your picker want to change the label value by comparing it with the min and max date, here the code *please swap the Ascending and descending if my code do wrong
- (IBAction)datePickerValueChanged:(id)sender {
NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init]; [dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate * maxDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: NSCalendarMatchStrictly];
[comps setYear: -50];
NSDate * minDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: NSCalendarMatchStrictly];
NSDate * curDate = self.dtPicker.date;
if(([curDate compare:minDate] == NSOrderedAscending)&& ([curDate compare:maxDate] == NSOrderedDescending)){
self.txtBirthday.text = [NSString stringWithFormat:#"%#",[dateFormat stringFromDate:self.dtPicker.date]];
}
}
class ViewController: UIViewController {
#IBOutlet weak var datePicker: UIDatePicker!
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.configureDatePicker()
}
private func configureDatePicker() {
let calendar = Calendar(identifier: .gregorian)
// 17 years less
let minimumDate = calendar.date(byAdding: .year, value: -17, to: Date())
// 50 years max. 17 + 33 = 50
let maximumDate = calendar.date(byAdding: .year, value: -50, to: Date())
self.datePicker.minimumDate = minimumDate
self.datePicker.maximumDate = maximumDate
}
#IBAction func onDatePickerChanged(sender: UIDatePicker) {
let dateFormtter = DateFormatter()
dateFormtter.dateStyle = .medium
self.label.text = dateFormtter.string(from: sender.date)
}
}
This code works fine without any issue. I think you have some issue in your code. UIDatePicker is resetting in some places.

How to set calendar type to Gregorian when app launch?

Does anyone know how to set calendar type to Gregorian when the app is launch? Most of users of the app that I created use Buddhist calendar, but I want to change it to Gregorian so Datepicker in the app use Gregorian.
Here is the code that I put in app delegate.
if (self.gregorian == nil) {
NSCalendar* temc = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
self.gregorian = temc;
}
You simply need to set the calendar property of your date picker.
Something like:
self.datePicker.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
or, if you have set your property,
self.datePicker.calendar = self.gregorian
There is no way to change the "default" calendar for your app so that date pickers implicitly use the Gregorian calendar.
Set your datePicker's calendar to gregorian type.
datePicker.calendar = Calendar(identifier: .gregorian)
date picker by default is Gregorian
var datePicker = UIDatePicker()
datePicker.calender = .gregorian

iOS NSDate to Single Digits

I am working on an app and I have this code:
NSDateFormatter *clockFormat = [[NSDateFormatter alloc]init];
[clockFormat setDateFormat:#"hh:mm a"];
self.clockLabel.text = [clockFormat stringFromDate:[NSDate date]];
[self performSelector:#selector(updateClockLabel) withObject:self afterDelay:1.0];
I created a view with subviews to create a LCD type clock display and I want to hide the correct subviews corresponding to the clockLabel. I created arrays of each view (digit), now how do I tell the views that if the first h in hh:mm is 1, hide these subviews to make an LCD "1" in the view.
Simply, how do I access each digit of hh:mm?
You can use NSRange to get substrings. Use NSRangeMake(location,length). To get an NSString of the first character of self.clockLabel.text. You can say say
NSString *firstHourDigit = [self.clockLabel.text substringWithRange:NSRangeMake(0,1)];

Setting UIDateTime Picker time zone

I have rather unusual requirement, but anyway..
#property (weak, nonatomic) IBOutlet UIDatePicker *dateDatePicker;
When I get reading of dateDatePicker.date it returns NSDate set to current system's time zone. But I want it to be in different specific time zone.
So, pretend right now it's 3:50pm Central Time.
dateDatePicker.date returns 3:50pm CST
I want to have something like this:
[dateDatePicker setTimeZone:#"EST"]
NSDate *ESTDate = dateDatePicker.date;
... and then I'd like debugger to show "2:50pm CST" - because 3:50pm in EST IS 2:50CST
This may be simpler that you think. If your date is 3:50pm CST, and you want it to be 2:50pm CST, just subtract an hour:
date = [date dateByAddingTimeInterval:-3600];
Of course, the local time zone might not always be CST, so you can get the difference between the two time zones and use that instead of hard coding -3600:
NSString *targetTimeZoneName = #"US/Eastern";
NSInteger localOffset = [[NSTimeZone localTimeZone] secondsFromGMTForDate:date];
NSInteger targetOffset = [[NSTimeZone timeZoneWithName:targetTimeZoneName] secondsFromGMTForDate:date];
NSInteger timeZoneDelta = localOffset - targetOffset;
date = [date dateByAddingTimeInterval:timeZoneDelta];
UIDatePicker's timeZone property is not a string, as you are using it. You have to pass it an NSTimeZone object.
Also, NSDates do not have a timezone. Its just a moment in history and its string representation depends on the time zone. Use an NSDateFormatter to format the date object for the timezone you want.

how to change toolbar item made in storyboard to show dynamic date

I had a similar question yesterday and I got part of my answer from there. But the thread got closed so this is kinda my follow-up question thread :)
original Q: How can I have a toolbar button/item change its date with [NSDate date]?
original A:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
yourToolBarItem = [NSString stringWithFormat:#"%#", [formatter stringFromDate:[NSDat date]]];
Followup Q: I have the toolbar made directly from navigationcontroller in storyboard . How can I reach its items programaticly and change item/object at index 0 to the current date.
I can't get my head around this. I have tried loads of types with [self navigationController.ToolbarItems] replacObjectAtIndexbut a big no for me so far.
Very helpful for any directive and help.
The easiest thing is to create a property for your button: #property IBOutlet UIBarButtonItem *myBarButton;
Then initialize it in viewWillAppear: myBarButton = [[UIBarButtonItem alloc] initWithTitle:(your date string) style: UIBarButtonItemStylePlain target:self action:(some action)];
// Of course you'll need to add it to the navigation bar here too...
Then when it's time to update the date on the button:
[myBarButton setTitle:(your date string)];
Hope that helps...

Resources