Update a Label daily with new text - nsdate

I have a label I want to update daily and automatically? in some specific time. How could the code be.. I have searched every where about how to updating the label daily.
the NSdate and NStimer label working . And also datepicker if the user want to look at forward events.
I think it is something with, 'if' the date is.. }else{... and something like that
Thanks
edit:
If I already have these codes in my app then there will be something wrong
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSDate *nowDate = [NSDate date];
self.currentDateLabel.text = [dateFormatter stringFromDate:nowDate];

Try this code for any comparison between dates... You should not compare date in the form of string. Compare the dates before conversion to string. Convert the self.serverDate into date format using dateFromString function of the formatter by specifying the exact date format as that of the dateString. Then compare the dates using following function.
-(void) callAfterSixtySecond:(NSTimer*) t
{
NSDate *today = [NSDate date]; // current date
NSDate *newDate = self.serverDate; // other date
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"HH:mm"];
NSDate *todayTime = [formatter dateFromString:[formatter stringFromDate:today]];
NSDate *requiredTime = [formatter dateFromString:[formatter stringFromDate:newDate]];
NSComparisonResult result;
result = [todayTime compare:requiredTime ]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"today is less");
else if(result == NSOrderedDescending)
NSLog(#"newDate is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same"); // time has reached. Update Label using setText method of label
else
NSLog(#"Date cannot be compared");
}
You will need to run this method every minute using an NSTimer...
NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
selector: #selector(callAfterSixtySecond:) userInfo: nil repeats: YES];

Related

NSTextfield storing in core data

i have a NSdatepicker and when i change the year, it changes another NSTextFile´s value to the number of years till now like this:
- ( IBAction)setExp:(id)sender {
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:#"yyyy"];
NSString *TodayString = [df stringFromDate:[NSDate date]];
NSString *TargetDateString = [df stringFromDate: startedPicker.dateValue ];
NSTimeInterval time = [[df dateFromString:TodayString] timeIntervalSinceDate:[df dateFromString:TargetDateString]];
int days = time /60 /60 / 24 /365;
NSString *intString = [NSString stringWithFormat:#"%d", days];
[expLbn setStringValue:intString];
}
but the new data from this action docent get stored in the core data for the NSTextField, if i type in a number in the same textfield the data gets stored.
i tryed http://www.red-sweater.com/blog/229/stay-responsive but can't make that work.

Formatting Date from server time to local time using NSTimeZone and Dateformatter

I am receiving a date/time as a NSString from my server where I am converting that time into a NSDate to the users local time using NSTimeZone. After which I try to reformat this NSDate into a better more readable NSString using the new NSDateFormatter format, however when I try to apply this new format it reverts the resulting dateString back to the original Server time.
I would like to know what I am doing wrong, I would like to show the converted time in the new format.
this is the code I am using
// set date format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
// change time to systemTimeZone
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:timeZone];
NSDate *localTime = [dateFormatter dateFromString:[singleInstanceActivationHistoryDictionay objectForKey:#"ActivationTime"]];
// reformat converted Time to readable format
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"dd/MM/yy - hh:mm a"];
NSString *dateWithNewFormat = [dateFormat1 stringFromDate:localTime];
NSLog(#"TimeZone - %#", timeZone);
NSLog(#"UTC ServerTime - %#", [singleInstanceActivationHistoryDictionay objectForKey:#"ActivationTime"]);
NSLog(#"UTC to deviceTimeZone - %#", localTime);
NSLog(#"NewFormat - %#", dateWithNewFormat);
This is an example of my output
TimeZone - Pacific/Auckland (NZST) offset 43200
UTC ServerTime - 2013-08-22 01:45:59
UTC to deviceTimeZone - 2013-08-21 13:45:59 +0000
NewFormat - 22/08/13 - 01:45 AM
any help would be greatly appreciated
The NSDateFormatter that reads the date must be set to the timezone that the date you are parsing is in, in your case, it is UTC. The date formatter will then be able to produce an NSDate object (which represents a specific moment in time regardless of timezones). You can then give that NSDate object to another NSDateFormatter that is configured to format dates in a specific time zone.
// set date format
NSDateFormatter *dateParser = [[NSDateFormatter alloc] init];
dateParser.dateFormat = #"yyyy-MM-dd HH:mm:ss";
dateParser.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSDate *specificMomentInTime = [dateParser dateFromString:[singleInstanceActivationHistoryDictionay objectForKey:#"ActivationTime"]];
// reformat converted Time to readable format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd/MM/yy - hh:mm a";
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:specificMomentInTime];
NSLog(#"UTC ServerTime - %#", specificMomentInTime);
NSLog(#"NewFormat - %#", dateWithNewFormat);

NSDateFormatter reports June 2, 2013 as being in week zero

I am using NSDateFormatter to convert a series of dates to a week number within a month.
The date formatting code I am using is yyyyMMW and everything I have read tells me that W will be between 1-5.
But, the 2nd of June 2013 fell on a Sunday (the default start day of the week in the gregorian calendar) and it's week number is reported as 0 even though the start date of the week is calculated correctly:
2013-06-03 14:15:45.611 date=20130531, week=2013055, start of week=20130526
2013-06-03 14:15:45.612 date=20130602, week=2013060, start of week=20130602
2013-06-03 14:15:45.612 date=20130603, week=2013061, start of week=20130602
Some quick and dirty test code to reproduce the log shown above:
NSDateFormatter *dateFormatDaily = [[NSDateFormatter alloc] init];
[dateFormatDaily setDateFormat:#"yyyyMMdd"];
NSDateFormatter *dateFormatterWeekly = [[NSDateFormatter alloc] init];
[dateFormatterWeekly setDateFormat:#"yyyyMMW"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setFirstWeekday:1]; // default but set here for clarity
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:5];
[dateComponents setDay:31];
[dateComponents setYear:2013];
NSDate *date_1 = [calendar dateFromComponents:dateComponents];
[dateComponents setMonth:6];
[dateComponents setDay:2];
NSDate *date_2 = [calendar dateFromComponents:dateComponents];
[dateComponents setDay:3];
NSDate *date_3 = [calendar dateFromComponents:dateComponents];
NSArray *datesToTest = #[date_1, date_2, date_3];
for (NSDate *date in datesToTest) {
NSString *weekNo = [dateFormatterWeekly stringFromDate:date];
NSDate *beginningOfWeek = nil;
BOOL rc = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate:date];
if (rc) {
NSLog(#"date=%#, week=%#, start of week=%#", [dateFormatDaily stringFromDate:date], weekNo, [dateFormatDaily stringFromDate:beginningOfWeek]);
} else {
NSLog(#"Could not calculate beginning of week");
}
}
Any ideas? A week number of 0 under any circumstances seems wrong to me.
Thanks
There are various parameters that cause this effect. First of all, you did not set a calendar for the date formatter. If you add
[dateFormatterWeekly setCalendar:calendar];
to your code, then the output will be as you expected:
date=20130531, week=2013055, start of week=20130526
date=20130602, week=2013062, start of week=20130602
date=20130603, week=2013062, start of week=20130602
But in your case, the date formatter uses the current calendar, and therefore has separate parameters firstWeekDay and minimumDaysInFirstWeek. These parameters are locale dependent. If I test this on the iOS Simulator with the "Region Format" set to "German -> Germany", then
[[dateFormatterWeekly calendar] firstWeekday] = 2
[[dateFormatterWeekly calendar] minimumDaysInFirstWeek] = 4
and I assume that you will have similar values, because now I get the same output as you.
Now for the date formatter, the week starts on a Monday, which means that June 2 is in the week starting at May 27. This counts as "week #0" in June, because only one day of this week is in June, but minimumDaysInFirstWeek = 4. The first week in a month that has at least
minimumDaysInFirstWeek days, counts as "week #1".
(I found the relevance of the minimumDaysInFirstWeek parameter here:
http://www.cocoabuilder.com/archive/cocoa/326845-week-of-month-confusion.html)

Problems converting a NSDate to a string

This extremely simple task was apparantly very hard...
NSDate *date;
date = [someMethod here];
//I've checked with debugger that the method returns an object of type NSDate.
//The description of date at this point is: "2012-02-02 19:42:00 +0000"
NSDateFormatter *dateFormat;
[dateFormat setDateFormat:#"dd-MM-yy hh:mm"];
NSString *dateString = [dateFormat stringFromDate:date];
dateString is just NIL
Does anyone know what's wrong?
Edit: What i really want to achieve is simply:
NSString *receivedDate = #"2012-02-02T20:42:00+01:00";
NSString *fixedDate = [do some magic]
//value of fixedDate is now: "02-02-12 20:42"
As Anna said you need to allocate an instance of NSDateFormatter because all you get is a NULL ptr, which just ignores the messages setDateFormat and stringFromDate, leaving you with NULL.
But also your format is for hours is incorrect. Refer to Date Formatter reference
This works for me:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:##"dd-MM-yy HH:mm"];
NSString *dateString = [df stringFromDate:date];

ios4 - splitting a date and time from a string into two separate strings

I have a JSON feed coming into my app, one of the fields is a combined date & time string which I need to split into discrete date and time strings for display in a table cell. An example of input from the JSON is:
2012-01-18 14:18:00.
I'm getting a bit confused with the date formatter, and clearly I'm not doing it right - I've tried a number of tutorials but most just seem to show how to format a date.
I've tried something a little like this to get just the time:
NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"h:mma"];
NSDate *raceDate = [dateFormat dateFromString:[rowData valueForKey:#"race_time"]];
NSString *raceTime = [dateFormat stringFromDate:raceDate];
but on output raceTime is just null.
Any help appreciated.
maybe the format should be more like
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
have a look at http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
might clear things up abit
Right, I have this working - it's probably a bit messy but here's what I did:
NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate* raceDate = nil;
NSError* dateError = nil;
NSRange dateRange = NSMakeRange(0, [[rowData valueForKey:#"race_time"] length]);
[dateFormat getObjectValue:&raceDate forString:[rowData valueForKey:#"race_time"] range:&dateRange error:&dateError];
[dateFormat setDateFormat:#"HH.mm"];
NSString *raceTime = [dateFormat stringFromDate:raceDate];
I can now output raceTime as a standalone time. I had to use getObjectValue:forString:range:error: to parse the original string to a date before changing the formatting and parsing it again.
As I'm using this in a table I suspect I'll need to use a static formatter so it doesn't slow everything down - if anyone can give a best practice on doing that I'd appreciate it.
If you are sure that the input string format wouldn't change – you might use something similar to:
NSString *date = nil;
NSString *time = nil;
NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];
NSString *raceTime = [rowData valueForKey:#"race_time"];
NSArray *dateParts = [raceTime componentsSeparatedByString:#" "];
if ([dateParts count] == 2) {
date = [dateParts objectAtIndex:0];
time = [dateParts objectAtIndex:1];
}

Resources