I am trying to use data that I have placed on the same class but in a different method (I believe that is the terminology) but I cannot seem to access this data for some odd reason. I can do so when I place it all together (in the timer) but that would consume a TONNE of memory would it not since it would be setting this data over and over. Anyway, this is my code so far:
/////////////////////////////////SET TIME/DAYS///////////////////
currentTime = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
self.timeNow.text = [timeFormatter stringFromDate:currentTime];
NSDate *lesson1Start = [timeFormatter dateFromString:#"8:40"];
NSDate *lesson2Start = [timeFormatter dateFromString:#"9:35"];
NSDate *recessStart = [timeFormatter dateFromString:#"10:30"];
NSDate *caregroupStart = [timeFormatter dateFromString:#"10:50"];
NSDate *lesson3Start = [timeFormatter dateFromString:#"11:00"];
NSDate *lesson4Start = [timeFormatter dateFromString:#"11:55"];
NSDate *lunchStart = [timeFormatter dateFromString:#"12:50"];
NSDate *lesson5Start = [timeFormatter dateFromString:#"1:30"];
NSDate *lesson6Start = [timeFormatter dateFromString:#"2:20"];
NSDate *endDay = [timeFormatter dateFromString:#"3:10"];
}
//////////////////////////END SET TIMES/////////////////////////
- (void)updateTime {
NSString *mondayDay = (#"Monday");
NSString *tuesdayDay = (#"Tuesday");
NSString *wednesdayDay = (#"Wednesday");
NSString *thursdayDay = (#"Thursday");
NSString *fridayDay = (#"Friday");
[updateTimer invalidate];
updateTimer = nil;
currentTime = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
self.timeNow.text = [timeFormatter stringFromDate:currentTime];
updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:#selector(updateTime)
userInfo:Nil repeats:YES];
///////Check day/time & update lesson/////
if (self.dayNow.text == mondayDay && self.timeNow.text == lesson1Start) {
NSLog(#"");
}
As you can see, I cannot use "lesson1Start" since it is not in - (void)updateTime.
Would it be fine if I did bundle it all noting that it would be setting this data over and over since it is placed in the timer.
PS: I am trying to check if when the lesson starts and if the time is when the lesson starts then the lesson would appear. In this case I just have NSLog(#"").
You can do as...
Lets consider your code is in class ClassRoom;
#interface ClassRoom
{
NSArray *scheduleArray; //instance variable
}
you can create a NSArray *scheduleArray; for holding //you have to allocate and init it in implementation file
NSDate *lesson1Start = [timeFormatter dateFromString:#"8:40"];
NSDate *lesson2Start = [timeFormatter dateFromString:#"9:35"];
NSDate *recessStart = [timeFormatter dateFromString:#"10:30"];
NSDate *caregroupStart = [timeFormatter dateFromString:#"10:50"];
NSDate *lesson3Start = [timeFormatter dateFromString:#"11:00"];
NSDate *lesson4Start = [timeFormatter dateFromString:#"11:55"];
NSDate *lunchStart = [timeFormatter dateFromString:#"12:50"];
NSDate *lesson5Start = [timeFormatter dateFromString:#"1:30"];
NSDate *lesson6Start = [timeFormatter dateFromString:#"2:20"];
NSDate *endDay = [timeFormatter dateFromString:#"3:10"];
add all above dates in scheduleArray.(Hope you know how to add items in NSArray.)
Now you can write updateTime as
- (void)updateTime {
NSString *mondayDay = (#"Monday");
NSString *tuesdayDay = (#"Tuesday");
NSString *wednesdayDay = (#"Wednesday");
NSString *thursdayDay = (#"Thursday");
NSString *fridayDay = (#"Friday");
[updateTimer invalidate];
updateTimer = nil;
currentTime = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
self.timeNow.text = [timeFormatter stringFromDate:currentTime];
updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:#selector(updateTime)
userInfo:Nil repeats:YES];
///////Check day/time & update lesson/////
for(NSDate * date in scheduleArray){
here you will get above saved dates use them to your need.
}
}
Hope it helps !
Related
NSDate object is working for iPhone, iPad when i ran the application in real devices. But when I run the application in iPad real device than it gives <not an Objective-C object> error. I tried to sort out it. but couldn't.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}
- (NSDate*) getDateFromJSON:(NSString *)dateString
{
// Expect date in this format "/Date(1268123281843)/"
int startPos = [dateString rangeOfString:#"("].location+1;
int endPos = [dateString rangeOfString:#")"].location;
NSRange range = NSMakeRange(startPos,endPos-startPos);
unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
NSTimeInterval interval = milliseconds/1000;
return [NSDate dateWithTimeIntervalSince1970:interval];
}
because of this issue i initialize the NSDate object and saw the date value. (NSDate *_Date = [NSDate alloc] init];) in here also gives same error? why is that? anyone faced this error ??
First off you can just remove this line:
NSDate *_Date = [NSDate alloc] init];
Since the next line just redeclares it, also you in the line you should remove you are missing a [.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
// Not needed since the line after it also declares the variable.
//NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}
When passing dates over the wire from client to server and back again, I format the date to a string for JSON using the format #"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" with the #"en_US_POSIX" locale. The same formatter provides an instance of NSDate from the date strings returned from the server to the client.
To test the conversions, I am trying to use NSDateComponents and NSCalendar to generate an independent date to use to validate the date from the formatter. However, the NSDate instances created from the NSCalendar and NSDateComponents vary ever so slightly from the NSDate instances provided by the NSDateFormatter. I do not understand why. Different dates produce a different number of variances. I apologize for yet another NSDate/NSDateFormatter question, but hope you find it somewhat novel.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSMutableArray *valuesWithError = [NSMutableArray arrayWithCapacity:750];
NSMutableArray *valuesThatMatch = [NSMutableArray arrayWithCapacity:250];
for (NSInteger milliseconds = 0; milliseconds < 1000; milliseconds++) {
NSString *dateString = [NSString stringWithFormat:#"2001-01-01T00:00:00.%03dZ", milliseconds];
NSLog(#"%#", dateString);
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *dc = [[NSDateComponents alloc] init];
dc.year = 2001;
dc.month = 1;
dc.day = 1;
dc.hour = 0;
dc.minute = 0;
dc.second = 0;
NSDate *expectedDate = [calendar dateFromComponents:dc];
NSTimeInterval baseInterval = [expectedDate timeIntervalSinceReferenceDate];
double mulitplier = 0.001;
NSTimeInterval millisecondsToAdd = milliseconds * mulitplier;
baseInterval += millisecondsToAdd;
expectedDate = [NSDate dateWithTimeIntervalSinceReferenceDate:baseInterval];
NSDate *dateFromFormat = [dateFormatter dateFromString:dateString];
NSTimeInterval expectedDateFromReferenceDate = [expectedDate timeIntervalSinceReferenceDate];
NSTimeInterval dateFromFormatFromReferenceDate = [dateFromFormat timeIntervalSinceReferenceDate];
NSTimeInterval differenceByTimeIntervalSubtraction = ABS(expectedDateFromReferenceDate - dateFromFormatFromReferenceDate);
NSTimeInterval differenceByTimeIntervalFromDate = [expectedDate timeIntervalSinceDate:dateFromFormat];
if (![expectedDate isEqualToDate:dateFromFormat]) {
NSLog(#"Difference = %e", differenceByTimeIntervalSubtraction);
[valuesWithError addObject:#(milliseconds)];
} else {
[valuesThatMatch addObject:#(milliseconds)];
}
}
I'm trying to countdown from a NSDate and display it in hours and minutes. Like this: 1h:18min
At the moment my date is updating to a UILabel and counting down but displaying like this:
Here's the code I'm using. A startTimer method and a updateLabel method
- (void)startTimer {
// Set the date you want to count from
// convert date string to date then set to a label
NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init];
[dateStringParser setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.000Z"];
NSDate *date = [dateStringParser dateFromString:deadlineDate];
NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init];
[labelFormatter setDateFormat:#"HH-dd-MM-yyyy"];
NSDate *countdownDate = [[NSDate alloc] init];
countdownDate = date;
// Create a timer that fires every second repeatedly and save it in an ivar
NSTimer *timer = [[NSTimer alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateLabel) userInfo:nil repeats:YES];
}
- (void)updateLabel {
// convert date string to date then set to a label
NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init];
[dateStringParser setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.000Z"];
NSDate *date = [dateStringParser dateFromString:deadlineDate];
NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init];
[labelFormatter setDateFormat:#"HH-dd-MM"];
NSTimeInterval timeInterval = [date timeIntervalSinceNow]; ///< Assuming this is in the future for now.
self.deadlineLbl.text = [NSString stringWithFormat:#"%f", timeInterval];
}
thanks for any help
- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval
{
NSInteger ti = (NSInteger)interval;
NSInteger seconds = ti % 60;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600);
return [NSString stringWithFormat:#"%02i:%02i:%02i", hours, minutes, seconds];
}
Since you use NSTimeInterval ,you are getting the time interval ,ie the difference, in seconds, to display it in hours and minutes you need to apply mathematics logic and convert it!
You many need a few loops to do it.
try this
Regards
That's the short story.
I have a nib with 6 UILabels for 6 different times.
The goal:
UILabel1 - calculate 90 minutes from current time
UILabel2 - 90 minutes from UILabel1 (or just 180 minutes from current time)
repeat, etc...
I can currently display the current times but I'm not sure how to calculate the times I need (see above).
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime1 = [dateFormatter stringFromDate:today];
NSString *currentTime2 = [dateFormatter stringFromDate:today];
NSString *currentTime3 = [dateFormatter stringFromDate:today];
NSString *currentTime4 = [dateFormatter stringFromDate:today];
NSString *currentTime5 = [dateFormatter stringFromDate:today];
NSString *currentTime6 = [dateFormatter stringFromDate:today];
timeLabel1.text = currentTime1;
timeLabel2.text = currentTime2;
timeLabel3.text = currentTime3;
timeLabel4.text = currentTime4;
timeLabel5.text = currentTime5;
timeLabel6.text = currentTime6;
}
Thanks in advance!
sidenote:I have found this to be a such a great place to find answers over the last 2 years!
Date with 90 minutes from current time
NSDate *nextDate = [NSDate dateWithTimeIntervalSinceNow:60*90];
Then
NSString *currentTime2 = [dateFormatter stringFromDate:nextDate ];
timeLabel2.text = currentTime2;
NSDate has the class method dateWithTimeIntervalSinceNow: for this.
I'm very new to iPhone development, and I'm trying to write a function which will accept one parameter, and return the current date/month and store it in a variable.
But I'm getting a (null) value with NSLog.
Method:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [[NSDate alloc] init];
if (type==#"month") {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if (type==#"day") {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
//int setDate = theDate;
[dateFormat release];
return theDate;
}
[now release];
return NULL;
}
Calling the function to get value:
NSString *month = [self getNowDateMonth:#"month"];
NSLog(#"%#", month);
Am I going about this the right way?
First of all, compare the strings using [#"month" isEqualToString:type], because two strings containing the same text ("month") may not be equal by the == operator. == checks if they're the same string object, not strings object with the same contents.
Second of all, you're leaking the date when returning the month or day (not releasing now). You should use [NSDate date]; instead of [[NSDate alloc] init].
To sum up, a suggested better version of this method would be:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [NSDate date];
if ([#"month" isEqualToString:type]) {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if ([#"day" isEqualToString:type]) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
[dateFormat release];
return theDate;
} else {
return nil;
}
}
Also, there are a few other points that can be taken into consideration to improve this method:
do not use NSString as type; use an enum
do not allocate NSDateFormatter on each call to the method; instead use a static variable in the method
You want to use NSDateComponents to reliably and easily extract unit information i.e. month, day, week etc from an NSDate.
See Date and Time Programming Guide for Cocoa.
Dates are a deceptively complex programing problem so Cocoa has a fully developed set of classes for dealing with them. However, the learning curve is a bit steep.