iOS : Move forward dynamically NSDate with button - iphone

I have created a custom class for my dates and need move dates forward and backward via button . Here is my code which shows Today date :
- (NSString *) showToday {
NSCalendar *myCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:myCal];
offsetComponents = [[NSDateComponents alloc] init];
//shows today
[offsetComponents setDay:0];
NSDate *nextDate = [myCal dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
[dateFormatter setDateFormat:#"d"];
NSString *currDay = [dateFormatter stringFromDate:nextDate];
[NSString stringWithFormat:#"%#",currDay];
[myCal release];
[dateFormatter release];
return currDay;
}
on my viewController :
customClass = [[customClass alloc]init];
day.text = [cal showToday];
so if I need to move forward a date I just change this line code to :
//show tomorrow
[offsetComponents setDay:1];
so How can I dynamically change this line and change dates via button ?

You can declare an int for your offsetComponents variable. then :
- (IBAction)moveDatesForward:(id)sender {
NSCalendar *persCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSPersianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *IRLocal = [[NSLocale alloc] initWithLocaleIdentifier:#"fa_IR"];
[dateFormatter setLocale:IRLocal];
[dateFormatter setCalendar:persCalendar];
offsetComponents = [[NSDateComponents alloc] init];
offsetComponents.day = _dayNumber;
NSDate *nextDate = [persCalendar dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
[dateFormatter setDateFormat:#"d"];
dayLabel.text = [dateFormatter stringFromDate:nextDate];
[NSString stringWithFormat:#"%#",dayLabel];
[persCalendar release];
[dateFormatter release];
_dayNumber ++;
}

How about doing something like this:
(Uses ARC - Don't complain about memory leaks.)
- (void) refreshDateLabel
{
NSDateFormatter* dateFormatter = [NSDateFormatter new];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
self.dateLabel.text = [dateFormatter stringFromDate: self.date];
}
- (IBAction)forward:(id)sender
{
self.date = [self.date dateByAddingTimeInterval: 24 * 60 * 60];
[self refreshDateLabel];
}
- (IBAction)back:(id)sender
{
self.date = [self.date dateByAddingTimeInterval: -(24 * 60 * 60)];
[self refreshDateLabel];
}
Complete project at https://github.com/st3fan/StackOverflowAnswers/blob/master/DateSelection

Related

EKCalender creates calendar but can't see it in iCal

I am trying to create a new calendar in iCal. Now I am able to create a new Calendar with some name. But my problem is when I try to create to Local calendar I cant see it in calendar list. Any one have any idea about this? I have tried using all types of sources but not able to find exact solution for this.
Thank you in advance.
NSMutableArray *arrAlarm = [[NSMutableArray alloc]init];
EKAlarm *alarm1 = [EKAlarm alarmWithRelativeOffset:3600];
EKAlarm *alarm2 = [EKAlarm alarmWithRelativeOffset:-3600]; //86400 1 day
[arrAlarm addObject:alarm1];
[arrAlarm addObject:alarm2];
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *ekevent = [EKEvent eventWithEventStore:eventStore];
ekevent.title = strname;
NSLog(#"%#",ekevent.startDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE MMM d,yyyy"];
NSDate *date = [dateFormatter dateFromString:strdate];
// Convert to new Date Format
[dateFormatter setDateFormat:#"YYYY-MM-DD HH:MM:SS ±HHMM"];
NSString *newDate = [dateFormatter stringFromDate:date];
// dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
// [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:#"hh:mm a"];
NSDate* firstDate = [dateFormatter dateFromString:time];
NSDate* secondDate = [dateFormatter dateFromString:endtime];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
// Convert to new Date Format
[dateFormatter setDateFormat:#"HH:MM"];
NSString *t11 = [dateFormatter stringFromDate:firstDate];
NSString *t12 = [dateFormatter stringFromDate:secondDate];
NSDate *dt1 = [dateFormatter dateFromString:t11];
NSDate *dt2 = [dateFormatter dateFromString:t12];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"hh"];
NSString *hourstring = [NSString stringWithFormat:#"%#",
[df stringFromDate:dt1]];
[df setDateFormat:#"mm"];
NSString *minstring = [NSString stringWithFormat:#"%#",
[df stringFromDate:dt1]];
[df release];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: [hourstring intValue]];
[components setMinute: [minstring intValue]];
[components setSecond: 00];
// NSDate *newDate = [gregorian dateFromComponents: components];
[gregorian release];
ekevent.startDate = date;
ekevent.endDate = [[NSDate alloc] initWithTimeInterval:timeDifference sinceDate:date];
[ekevent setCalendar:[eventStore defaultCalendarForNewEvents]];
ekevent.alarms = arrAlarm;
[arrAlarm release];
NSError *err;
[eventStore saveEvent:ekevent span:EKSpanThisEvent error:&err];
Try this code you will get the desired result.

Splitting time to 10 mins interval in iphone

i want to split the time in the interval of 30mins, so i can get time like this:
12:00 AM 12:10 AM 12:20 AM .......... till 11:50 PM.
i'm trying something like this :
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSLog(#"Start time %#",fromTime);
NSLog(#"End time %#",toTime);
NSDate *dateByAddingThirtyMinute;
dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:1800];
NSString *formattedDateString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(#"Time after 10 min %#",formattedDateString);
but i am able to print the first ten minute splitting ...
can any one help me how to loop it ...
Both of the other answers are wrong, because they do not account for daylight savings time. To do that, you have to use NSDateComponents and NSCalendar:
NSDate *startDate = ...;
NSDate *endDate = ...;
NSDateComponents *diff = [[NSDateComponents alloc] init];
[diff setMinute:0];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *tmp = startDate;
NSMutableArray *dates = [NSMutableArray arrayWithObject:tmp];
while ([tmp laterDate:endDate] == endDate) {
[diff setMinute:[diff minute] + 10];
tmp = [cal dateByAddingComponents:diff toDate:startDate options:0];
[dates addObject:tmp];
}
In this code, I'm not actually running the NSDate objects through the NSDateFormatter, because that should happen at a different level. This code is all about the underlying data (the Model), and NSDateFormatter usually operates at the user-visible level (the View). Plus, it's generally more useful to have the raw data object than the formatted string.
Try with below code
NSString *startTime = #"12:00 AM";
NSString *endTime = #"11:40 AM";
NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease];
[timeFormat setDateFormat:#"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSDate *dateByAddingThirtyMinute ;
NSTimeInterval timeinterval = [toTime timeIntervalSinceDate:fromTime];
NSLog(#"time Int %f",timeinterval/3600);
float numberOfIntervals = timeinterval/3600;
NSLog(#"Start time %f",numberOfIntervals);
for(int iCount = 0;iCount<numberOfIntervals*6 ;iCount ++)
{
dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:600];
fromTime = dateByAddingThirtyMinute;
NSString *formattedDateString;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm a"];
formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(#"Time after 10 min %#",formattedDateString);
}
Try this out
int numberOfIntervals = [toDate timeIntervalSinceDate:fromDate]/(10*60);
for (int i = 0; i < numberOfIntervals; i++) {
NSDate *theDate = [date dateByAddingTimeInterval:i * 60 * 10];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSString *formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(#"Time after 10 min %#",formattedDateString);
[dateFormatter release];
}

unable to fetch NSDate from NSString

I am able to fetch NSString representing the current date and time in PST using the following code.
//get current date and time
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:#"America/Los_Angeles"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yy HH:mm:ss zzz"];
[dateFormatter setTimeZone:timeZone];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[enUSPOSIXLocale release];
NSDate *date = [NSDate date];
NSString *currentDateStr = [dateFormatter stringFromDate:date];
NSLog(#"currentDateStr %#",currentDateStr);
[dateFormatter release];
EDIT:
But the following code to fetch NSDate from NSString doesn't serve my purpose.
//get date from string
NSDateFormatter* formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"MM/dd/yy HH:mm:ss"];
NSDate *dt = [[NSDate alloc]init];
dt = [formatter2 dateFromString:currentDateStr];
NSLog(#"dt %#",dt);
"dt" appears to be null.
Could anybody help me out in solving this issue of getting NSDate from NSString.
Thanx in advance.
NSDateFormatter also has dateFromString: function.
EDIT:
//get date from string.
NSDateFormatter* formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"MM/dd/yy HH:mm:ss zzz"];
NSDate *dt = [formatter2 dateFromString:currentDateStr];
NSLog(#"dt %#",dt);
Make use of
[dateFormatter dateFromString:urString];
In your case urString is currentDateStr
Use
- (NSString *)datePickerValueChangedd:(UIDatePicker*) datePicker{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 50, 68, 68)];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label.text = [NSString stringWithFormat:#"%#",[df stringFromDate:datePicker.date]];
NSLog(#"I am inside the datePickerValueChanged - - %#", label.text);
[df release];
globalVariable= label.text;
return (label.text);
}

convert string into NSDate

i have a "DateTimeArray" this array contain
DateTimeArray[index 0] = 20.05.2011 12:12:50
DateTimeArray[index 1]= 20.05.2011 12:13:20
DateTimeArray[index 2]= 20.05.2011 12:20:10
all the value are in string,and i want to convert this string into NSDate and only want to access time not date
and then this time values will be stored in array and this newly array will be used for drawing line chart
i hope some one know this issue
thank you very much
Code as follows,
for(int index=0;index<[DateTimeArray count];index++)
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm:ss"];
NSString *timeString=[[[DateTimeArray objectAtIndex:index]componentsSeparatedByString:#" "]objectAtIndex:1];
NSDate *time=[df dateFromString:timeString];
[timeArray addObject:time];
[df release];
}
Try this
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm:ss"];
NSDate *formattedDate = [df dateFromString:[DateTimeArray objectAtIndex:requiredIndex]];
[df release];
Best and cleaner approach:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd.MM.yyyy HH:mm:ss"];
for(int i=0; i < [DateTimeArray count]; ++i)
{
NSString *string = [DateTimeArray objectAtIndex:i];
NSDate *date = [df dateFromString:string];
[timeArray addObject:time];
}
[df release]; // ALWAYS release unused objects
Then to just access hours, and not days, you should select the required components of each NSDate* instance:
// Get the Gregorian calendar
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Get the date
NSDate* date = [timeArray objectAtIndex:my_index];
// Get the hours, minutes, seconds
NSDateComponents* hour = [cal components:NSHourCalendarUnit fromDate:date];
NSDateComponents* minute = [cal components:NSMinuteCalendarUnit fromDate:date];
NSDateComponents* second = [cal components:NSSecondCalendarUnit fromDate:date];
NSMutableArray *nsdateArray = [NSMutableArray arrayWithCapacity:[DateTimeArray count]];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd.MM.yyyy HH:mm:ss"];
for(NSString *currentString in DateTimeArray){
NSDate *date = [dateFormat dateFromString:currentString];
[nsdateArray addObject:date];
}
[dateFormat release];
NSLog(#"ArrayWithDate:%#",[nsdateArray description]);
Heres the complete set of code.. Hope it helps..
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
int i=0;//start for{} loop
NSString *currDate = [formatter dateFromString:[DateTimeArray objectAtIndex:i]];
[formatter release];
Happy iCoding...
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"]
NSString *theTime = [timeFormat dateFromString:date];
or
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(kCFCalendarUnitHour | kCFCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

Updating time in iphone sdk

I'm using the code provided below to display time and date. can anyone help me with atuomatically changing the time by seconds and the date by the day?
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSLog(#"\n"
"theDate: |%#| \n"
"theTime: |%#| \n"
, theDate, theTime);
[dateFormat release];
[timeFormat release];
[now release];
You can use NSTimer, specifically scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:. You can use 1 as a time interval.
Use the NSDateComponents class. For example, to add one day and one second to a date:
NSDate *startDate = [NSDate date];
unsigned unitFlags = NSDayCalendarUnit | NSSecondCalendarUnit;
NSCalendar *curr = [NSCalendar currentCalendar];
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
oneDay.day = 1;
oneDay.second = 1;
NSDate* adjustedDate = [curr dateByAddingComponents:oneDay
toDate:startDate
options:0];
Date and Time programming guide