How to make a label show on a specific time in xcode - iphone

I'm making an iOS application for iPhone, and I want to have two labels that is hidden on a specific time and shown on a specific time. Like Label1 is shown between 6am and 6pm and Label2 is shown between 6pm and 6am
Any ideas?

[NSDate date]; gives you the current date .Use date fromatter to get the fromat you need and use setText: method to set the text.Fire it in a timer and set the text
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEEE MMMM d, YYYY"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
[yourLabel setText:[dateFormatter stringFromDate:[NSDate date]]];
EDIT
full code,Try this
-(void)showtext
{
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"hh:mm:ss"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
if( [self compareTimeIsbetween6])
{
[self.date1Label setHidden:NO];
[self.date2Label setHidden:YES];
[self.date1Label setText:[dateFormatter stringFromDate:[NSDate date]]];
}
else
{
[self.date1Label setHidden:YES];
[self.date2Label setHidden:NO];
[self.date2Label setText:[dateFormatter stringFromDate:[NSDate date]]];
}
}
-(BOOL)compareTimeIsbetween6
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];
if (currentHour < 6 || (currentHour > 18 || (currentHour == 18 && (currentMinute > 0 || currentSecond > 0)))) {
return YES;
}
else
{
return NO;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(showtext) userInfo:nil repeats:YES]; // Do any additional setup after loading the view, typically from a nib.
}
.h
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *date1Label;
#property (weak, nonatomic) IBOutlet UILabel *date2Label;

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
Now you have the hour, just add your normal logic.
if want to be change the formate do this...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"];
// another is [formatter setDateFormat:#"hh:mm:ss"];
NSLog(#"Current Date: %#", [formatter stringFromDate:today]);

Related

NSDateFormatter not working to set setTimeZone

I am trying to know the difference between two dates (Including days,hours,minutes and seconds). For that I am using below code, but It's not working.
+ (void)UpdateTableViewCellWithNSTimer:(NSString *)gameTime :(UIView *)inputView{
NSDate *now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[NSLocale systemLocale]];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
[outputFormatter setDateFormat:#"mm/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:gameDate toDate:now options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
UITableView *dynamicTable = (UITableView *)[inputView viewWithTag:55];
NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:4 inSection:0];
UITableViewCell *currentCell = [dynamicTable cellForRowAtIndexPath:cellIndexPath];
NSString *challengeStartsIn=[NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)];
NSString *Mystring =[NSString stringWithFormat:#"%# %#", #"ChallengeStartsIn", challengeStartsIn];
currentCell.textLabel.text = Mystring;
}
**Game and now dates on logs are:**
2013-05-18 11:36:42.609 FPPresent[2213:5203] gametime value=05/19/2013 5:30 AM
2013-05-18 11:36:42.610 FPPresent[2213:5203] now=2013-05-18 06:06:42 +0000
After using outputformatter:
gametime value =2013-01-19 00:00:00 +0000(It should be 2013-01-19 05:30:00 +0000 )
now=2013-05-18 06:10:07 +0000(should be : 2013-05-18 11:40:07 +0000)
The game date and now date should in localTimeZone. But, even I try to set
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
My data format is showing (Exactly 5.30 hours different, our local time zone is GMT+5.30)
Please let me know where I am going wrong
[NSDate date] is taking default timezone as GMT. so, I am unable to set my local timezone to date.
While knowing the difference between GMT OFFset to local , I am able to get the difference between two dates sucessfully.
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setLocale:[NSLocale currentLocale]];
[outputFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSDate* gameDestinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:gameDate];
// NSLog(#"gameDate=%#",gameDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:destinationDate toDate:gameDestinationDate options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
return ([NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)]);
Are you setting the timeZone for the output formatter and along with that are you adding the time difference to the output date?? Because, there is not need to add the time difference as setting timezone for both dateFormatters will automatically take care of the time difference between the time zones.

Separate Hours, Mins and Seconds in xcode

I have created one alarm clock application.
In which, when user clicks on the Set Timer Button, Picker view gets called.
Picker view displays Hours, Mins and Seconds.
When User select them and clicks on Ok, then That Timer Button Value Gets changed.
For Example:
If User Selects 2 Hours , 4 mins and 10 Seconds then
Button Label will be 02:04:10
Now i want to Separate all 3 things like 2 will be stored in one string, 4 will be in other and 10 in some other string.
What should i do here?
Can Anyone please help?
Try this think may be helped you ....
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"<your date format goes here"];
NSDate *Yourcurrenttime = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: Yourcurrenttime];
NSInteger hour = [components hour];
NSInteger minutes = [components minute];
NSInteger seconds = [components second];
And Store the all value in the string.
NSString *HourSTR =[NSString stringWithFormat:#"%d",hour];
NSString *minutesSTR =[NSString stringWithFormat:#"%d",minutes];
NSString *secondsSTR =[NSString stringWithFormat:#"%d",seconds];
i done one count Down timer like this way may be its useful for you
-(void) viewWillAppear:(BOOL)animated
{
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats: YES];
}
AND
-(void) updateCountdown
{
NSString *dateString = #"14-09-2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:now];
NSDateComponents *componentMint = [calendar components:NSMinuteCalendarUnit fromDate:now];
NSDateComponents *componentSec = [calendar components:NSSecondCalendarUnit fromDate:now];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit
fromDate:now
toDate:dateFromString
options:0];
lblDaysSetting.text=[NSString stringWithFormat:#"%02d",componentsDaysDiff.day];
lblHouresSetting.text=[NSString stringWithFormat:#"%02d",(24-componentsHours.hour)];
lblMinitSetting.text=[NSString stringWithFormat:#"%02d",(60-componentMint.minute)];
lblSecSetting.text=[NSString stringWithFormat:#"%02d",(60-componentSec.second)];
}
now just set your logic

How can we set date in to date picker with string in a format like 12:30 AM?

Hello Everybody I want set date in to datepicker from string like above format given in the question
I m using following code to set date to datepicker
NSString *tmStr=[selectedDics objectForKey:#"Time"];
NSArray *timeStr=[tmStr componentsSeparatedByString:#" "];
NSString *fStr=[timeStr objectAtIndex:1];
NSArray *Time=[[timeStr objectAtIndex:0]componentsSeparatedByString:#":"];
NSInteger hour=[[Time objectAtIndex:0] intValue];
NSString *str=[NSString stringWithFormat:#"%i:%i",hour,[[Time objectAtIndex:1]intValue]];
NSString *a;
if ([fStr isEqualToString:#"PM"])
{
a=#"PM";
hour=hour+12;
}else
{
a=#"AM";
if (hour==12) {
hour=0;
}
}
NSCalendar *calender = [NSCalendar currentCalendar];
[calender setTimeZone:[NSTimeZone defaultTimeZone]];
unsigned currentFlag = NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *comps = [calender components:currentFlag fromDate:[NSDate date]];
comps.hour = hour;
comps.minute = [[Time objectAtIndex:1]intValue];
datePicker.date = [calender dateFromComponents:comps];
Is there another way to set it easily?
NSDateFormatter *formatter;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:mm a"];
NSDate *date=[formatter dateFromString:#"12:30 AM"];
[datepicker setDate:date];

disply the current week start and end date

I want to display the Current week in UINavigationBar and then click on Next or Previous button to display the Previous week or Next week
Example:
July 22 - July 28
July 29 - Auguest 4
To get first date of the week you can do something like this :
- (NSDate *)firstDayOfWeekFromDate:(NSDate *)date {
CFCalendarRef currentCalendar = CFCalendarCopyCurrent();
NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
[components setDay:([components day] - ([components weekday] - CFCalendarGetFirstWeekday(currentCalendar)))];
//[components setDay:(CFCalendarGetFirstWeekday(currentCalendar))];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
CFRelease(currentCalendar);
return [CURRENT_CALENDAR dateFromComponents:components];
}
After getting first week of the day you can calculate days as suggested in above answer by #vikas
:)
NSDate * selectedDate = [NSDate date];
-(IBAction)Week_CalendarActionEvents:(id)sender{
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
NSDate *nextDate;
if(sender==Week_prevBarBtn) // Previous button events
[offsetComponents setDay:-7];
else if(sender==Week_nextBarBtn) // next button events
[offsetComponents setDay:7];
nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:selectedDate options:0];
selectedDate = nextDate;
[selectedDate retain];
NSDateComponents *components = [gregorian components:NSWeekCalendarUnit fromDate:selectedDate];
NSInteger week = [components week];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM YYYY"];
NSString *stringFromDate = [formatter stringFromDate:selectedDate];
[formatter release];
[Week_weekBarBtn setTitle:[NSString stringWithFormat:#"%#,Week %d",stringFromDate,week]];
}

Split NSDate into year month date

If I have a date like 04-30-2006
how can I split and get month, day and year
Alsois there any direct way of comparing the years ?
you have to use NSDateComponents. Like this:
NSDate *date = [NSDate date];
NSUInteger componentFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:componentFlags fromDate:date];
NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];
Alsois there any direct way of comparing the years ?
not built in. But you could write a category for it. Like this:
#interface NSDate (YearCompare)
- (BOOL)yearIsEqualToDate:(NSDate *)compareDate;
#end
#implementation NSDate (YearCompare)
- (BOOL)yearIsEqualToDate:(NSDate *)compareDate {
NSDateComponents *myComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:self];
NSDateComponents *otherComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:compareDate];
if ([myComponents year] == [otherComponents year]) {
return YES;
}
return NO;
}
#end
to split it is easy
NSString *dateStr = [[NSDate date] description];
NSString *fStr = (NSString *)[[dateStr componentsSeparatedByString:#" "]objectAtIndex:0];
NSString *y = (NSString *)[[fStr componentsSeparatedByString:#"-"]objectAtIndex:0];
NSString *m = (NSString *)[[fStr componentsSeparatedByString:#"-"]objectAtIndex:1];
NSString *d = (NSString *)[[fStr componentsSeparatedByString:#"-"]objectAtIndex:2];
this will be easy to get things what you want basically .
All the answers so far assume you have an actual NSDate object, but in your post you say, "I have a date like 04-30-2006" which could be a string. If it is a string then Abizem's answer is the closest to what you want:
NSString* dateString = #"04-30-2006";
NSArray* parts = [dateString componentsSeparatedByString: #"-"];
NSString* month = [parts objectAtIndex: 0];
NSString* day = [parts objectAtIndex: 1];
NSString* year = [parts objectAtIndex: 2];
Or, using NSDateFormatter:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *now = [NSDate date];
[formatter setDateFormat:#"MM"];
NSString *month = [formatter stringFromDate:now];
[formatter setDateFormat:#"dd"];
NSString *day = [formatter stringFromDate:now];
[formatter setDateFormat:#"yyyy"];
NSString *year = [formatter stringFromDate:now];
[formatter release];
(code typed right here; caveat implementor)