How to set current date on NSDatePicker object in osx - objective-c

I am new to OSX App development. In one of the sample menubar Apps I did, I used an NSDatePicker object. But it is not displaying the current date. How can i display the current date using an NSDatePicker object.

Did you try
NSdate *currentDate = [NSDate date];
datePicker.date = currentDate;
??
this is the same as
NSdate *currentDate = [NSDate date];
[datePicker setDate:currentDate]
The main difference is that if currentDate is not equal to nil in your code, the datePicker's date does not get set!!

set current system time to Datepicker
#IBOutlet weak var txtStartTime: NSDatePicker!
swift
let now = Date()
txtStartTime.dateValue = now

As of OSX 10.4, the way to do this is
NSDate *currentDate = [NSDate date];
[datePicker setDateValue:currentDate];

You can set date to date picker in Swift 3.2like,
self.datePicker.dateValue = NSDate() as Date

Related

Getting NSDate from time string with UTC format

I am trying to get a NSDate object from a UTC time string. The example of the time string is this:
2016-07-29T11:43:55+02:00
I am usingNSDateFormatter and set the formate as: yyyy-MM-dd'T'HH:mm:ss
However this gives me the take with incorrect time zone. So the above date will be: 2016-07-29T09:43:55+00:00
How do I keep the time zone aspect as well?
I did try adding a 'Z' to the end of the formatter but that just returns a nil date.
Try this
NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[userFormatter setLocale:posix];
NSString *dateConverted = [userFormatter stringFromDate:theDate];
Thanks to all that help. Solved the issue. The time on my iOS Simulator was correct. However when I called [NSDate date]; it show'd me a time two hours before local time. Hence the 'errors' I was seeing in the formatting of NSDate.
Use NSISO8601DateFormatter if targeting iOS 10 and above. https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

How to convert this NSTimeInterval line from Swift to Objective-C

How to convert this into Objective-C ?
let date = NSDate(timeIntervalSinceReferenceDate: interval)
I tried this:
NSDate *date = [NSDate timeIntervalSinceReferenceDate: (interval)];
It generates an error of course.
Tells me: No known class method for selector timeIntervalSinceReferenceDate:
Also here is some context:
NSTimeInterval interval = [[NSDate alloc]init].timeIntervalSinceReferenceDate + [NSDate weekInSeconds].doubleValue;
NSDate *date = [NSDate timeIntervalSinceReferenceDate: (interval)];
return [self isSameWeekAsDate:(date)];
timeIntervalSinceReferenceDate: is not a method implemented on the NSDate class. When bridging from Objective-C to Swift, Swift does some renaming with initializers.
In order to initialize an NSDate object in Objective-C with a reference date, you must call either the class method dateWith... or the instance method initWith...:
NSDate * const date = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];
or...
NSDate * const date = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: timeInterval];
I've added the const here to make this more closely match the Swift code with the let declaration.

NSTimer time increment

I'm a beginner in obj-C for iOS platform and am trying to build a few simple project to build my foundation.
I have a button which increase the NSTimer time for the label, but when I use NSLog to log the time, it uses the value before time increment was implemented. I need to be able to log a updated time (after increment), as I require that value and am implementing more function into the IBAction after I solve this portion.
E.g at 15min I press, the NSLog will read it as "00:15:00.0" rather than "00:35:00.0".
- (IBAction)onSkipPressed:(id)sender {
startDate = [startDate dateByAddingTimeInterval:-1200];
NSLog(#"%#",self.timeLabel.text);
}
Any one know the reason for this issue? And how should I solve it such that NSLog will read it as "00:35:00.0" if I invoke this IBAction at 15min.
EDIT - The start button will start the timer and timeLabel will get the string. Sorry for missing out such a important detail. I don't think there are any other code in the project which is related to this functionality already. Thank you for pointing it out to me.
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.S"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
timeLabel.text = timeString;
}
my IBAction to fire the timer
- (IBAction)onStartPressed:(id)sender {
startDate = [NSDate date];
gameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
//hide start button and show timeLabel
startButton.hidden=true;
timeLabel.hidden=false;
}
I went back to do a few revision with tutorials involving NSTimer. And turns out all I was missing was 1 line [self updateTimer]
- (IBAction)onSkipPressed:(id)sender {
startDate = [startDate dateByAddingTimeInterval:-1200];
[self updateTimer];
NSLog(#"%#",self.timeLabel.text);
}
This solve my issue and the timeLabel.text is updated for me to log the information.
Um, why are you passing in negative 1200?
// this subtracts 1200 seconds from your date, no?
startDate = [startDate dateByAddingTimeInterval:-1200];
Shouldn't you do:
// add 30 minutes (60 seconds a minute x 30 minutes) to your time interval
startDate = [startDate dateByAddingTimeInterval:(60 * 30)];
...
NSLog(#"%#",self.timeLabel.text);
Or am I misunderstanding something?

NSDatePicker timezone weirdness

I have an NSDatePicker in my nib file. In code, I set it's timezone to be the GMT calendar's timezone:
[datePicker setTimeZone:[calendar timeZone]];
I only really care about the time (hours, minutes) on the datepicker which I populate programmatically:
NSDate *anyDate = [NSDate date];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:anyDate];
[components setHour:hours];
[components setMinute:minutes];
NSDate *newDate = [calendar dateFromComponents:components];
[datePicker setDateValue:newDate];
This correctly has the desired effect of setting the date pickers time to the time I want. So if hours is 8 and minutes is 30, the date picker shows 8:30. However, if I type an 8 into the hour field of the date picker it displays as a 3. Something weird is going on with timezones somewhere but I'm not sure where...
Seems like I'm not the first person to stumble across this issue. The solution, for those who are interested, I found here http://www.cocoabuilder.com/archive/cocoa/305254-nsdatepicker-weirdness-with-time.html. Apparently if you set the timezone of a date picker but not the calendar, you get this issue. The resolution is this:
[datePicker setTimeZone:[calendar timeZone]];
[datePicker setCalendar:calendar];

NSDate from NSString

I've read the DateFormatting guide and I'm still not able to get a working formatter.
NSString *string = #"0901Z 12/17/09";
//This is a sample date. The Z stands for GMT timezone
//The 0901 is 09h 01m on a 24 hour clock not 12.
//As long as I can get the hours/min & date from the string I can deal with the time zone later
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"hhmm'Z' MM/dd/yy"];
NSDate *date = [dateFormat dateFromString:string];
That works for me when I try it. Adding NSLog(#"%#", date) to the end of your code gives me this output:
2010-02-28 12:17:22.921 app[9204:a0f] 2009-12-17 09:01:00 -0800
What is the problem you're seeing?
Edit: I figured it out, you're not having a problem with 09:01, but with other 24-hour times, like 14:25, right? Change your formatter to:
#"HHmm'Z' MM/dd/yy"
Copied from a similar question I answered here: NSDateFormatter returns nil for #"dd-MM-yy" in iOS 3.0
If you're working with user-visible dates, you should avoid setting a date format string. Formatting dates this way is not localizable and makes it impossible to predict how your format string will be expressed in all possible user configurations. Rather, you should try and limit yourself to setting date and time styles (via -[NSDateFormatter setDateStyle:] and -[NSDateFormatter setTimeStyle:]).
On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ("en_US_POSIX" works the same on iPhone OS as it does on Mac OS X, and as it it does on other platforms).
Once you've set "en_US_POSIX" as the locale of the date formatter, you can then set the date format string and the date formatter will behave consistently for all users.
The above info and more can be found in Apple's Technical Q&A QA1480
Here's a snippet of code from my app which implements the above recommendation :
static NSDateFormatter* dateFormatter = nil;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc]
initWithLocaleIdentifier:#"en_US_POSIX"] autorelease];
NSAssert(enUSPOSIXLocale != nil, #"POSIX may not be nil.");
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
dateFormatter.dateFormat = #"EEE, dd MMM yyyy HH:mm:ss +0000";
}