Splitting time to 10 mins interval in iphone - 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];
}

Related

Incrementing a date's year by one if that date has already passed

I have an array containing birth dates like the one below:
Array(
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
Now I want to make a new array based on whether or not the date has passed. Writing this question in 2013, if a current date has passed then we will change that date's year to 2014. If it hasn't passed then we will have it stay the 2013 date.
For example:
NewArray(
"11/07/2013", no change cus this date hasnt passed yet
"07/10/2013", no change same as above
"20/02/2014" **as date has already passed thats why 2014**
I'm using the following code for this
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *curYear = [dateFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
for(int i = 0; i < [_newlymadeArray count]; i++)
{
NSString *dateStr = [_newlymadeArray objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
[dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
[_newlymadeArray replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",_newlymadeArray);
}
NSLog(#"_newlymadeArray%#",_newlymadeArray);
This is however what I get when I NSLog _newlymadeArray:
after replacing (
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
At index 2 it should be "20/02/2014" instead of the 2013 date. What might cause my problem and how can I solve it?
I've made some modifications to your code, and it is working as you want.
In my code I've compared date, which is in Ascending form of current date. If it satisfies the condition, then I've fetched YEAR from matched date, by the DateFormatter "yyyy". Then I simply increment this year by 1, and replace this year in old Date, which is "20/02/2013" to "20/02/2014"
array = [[NSMutableArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
NSDateFormatter *yrFormatter = [[NSDateFormatter alloc] init];
[yrFormatter setDateFormat:#"yyyy"];
NSString *curYear = [yrFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
NSLog(#"%#",curYear);
NSLog(#"%#",nextYear);
dateStr = [dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
NSLog(#"%#",dateStr);
[array replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",array);
}
NSLog(#"_newlymadeArray%#",array);
}
This seems to be working perfectly, so I hope it helps you.
Plese dear try to use this one.I think this one may help
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDate* newDate = [calendar dateByAddingComponents: components toDate:#"YourDate" options: 0];
Otherwise you can use this one code.
if (comResult == NSOrderedSame)
{
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSDate *date = [formatter dateFromString:#"11/07/2013"];
NSDate* newDate = [calendar dateByAddingComponents: components toDate:date options: 0];
// here replace your array object with this "newDate"
}
Compare your array date to today's date with NSDate compare function. Here are the details:
NSString *arrayDateString = #"20/02/2013" // fetch this string from your array
NSDate *todaysDate = [NSDate date];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy"];
NSDate* d = [df dateFromString:arrayDateString];
// now compare this date (d) with todaysDate using NSDate function
if ([d compare:todaysdate]== NSOrderedAscending)
{//write your code here}
If it results NSOrderedAscending, then it means array date is earlier than today's date.
So for that date, update year incremented by one using NSDateComponents:
NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.year = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
Or you can use NSDate function itself:
NSDate *now = arrayDate;
int yearsToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*365*year];
But second option is not full-proof - because of leap year problem.
Hope this two options help you, for solving your issue.
NSArray * array = [[NSArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSMutableArray *output = [NSMutableArray new];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSDate *date = [dateFormatter dateFromString:dateStr];
if ([date compare:now] == NSOrderedAscending)
{
[components setYear:1];
date = [calendar dateByAddingComponents:components toDate:date options:0];
}
dateStr = [dateFormatter stringFromDate:date];
[output addObject:dateStr];
}
NSLog(#"Result : %#",output);

iPhone: Date conversion issues

I need to check an event date, which should be between Current date and 60 days from now. The below code is used, but it is NOT working correctly. Please note, i'm getting event string like this - "2012-04-14T16:50:02Z" from my server.
// current date
double currDateInMilliSecs = [NSDate timeIntervalSinceReferenceDate] * 1000;
NSLog(#"currDateInMilliSecs: %f", currDateInMilliSecs);
// sixty days
double sixtydaysvalue = 60.0 * 24.0 * 3600.0 * 1000.0;
NSLog(#"sixtydaysvalue: %f", sixtydaysvalue);
// add current date + sixt days
double sixtyDaysMilliSecsFromCurrDate = currDateInMilliSecs + sixtydaysvalue;
NSLog(#"sixtyDaysMilliSecsFromCurrDate: %f", sixtyDaysMilliSecsFromCurrDate);
// check does the event date between current date + 60 days
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
//[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
// [eventDict objectForKey:#"begin_at"] gives date string like this "2012-04-14T16:50:02Z" for ex.
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
NSTimeInterval nowSinceEventDate = [eventdate timeIntervalSince1970];
NSLog(#"nowSinceEventDate: %f", nowSinceEventDate);
double eventDateInMilliSecs = nowSinceEventDate * 1000;
NSLog(#"eventDateInMilliSecs: %f", eventDateInMilliSecs);
// this is not working as expected
if ( eventDateInMilliSecs<sixtyDaysMilliSecsFromCurrDate && eventDateInMilliSecs>currDateInMilliSecs )
{
}
else
{
}
Any help please?
try this
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss SSS"];
Try this:
NSString *dateString = #"2012-04-14T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSTimeInterval nowSinceEventDate = [eventDate timeIntervalSince1970];
NSLog(#"interval = %f", nowSinceEventDate);
UPDATE:
NSString *dateString = #"2012-05-21T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:60];
NSDate *minDate = [NSDate date];
NSDate *maxDate = [gregorian dateByAddingComponents:components toDate:minDate options:0];
NSLog(#"eventDate interval = %f", [eventDate timeIntervalSince1970]);
NSLog(#"minDate interval = %f", [minDate timeIntervalSince1970]);
NSLog(#"maxDate interval = %f", [maxDate timeIntervalSince1970]);
BOOL isBetween = (([eventDate compare:minDate] == NSOrderedDescending) && ([eventDate compare:maxDate] == NSOrderedAscending));
NSLog(#"isBetween = %d", isBetween);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss:SSS"];
// [eventDict objectForKey:#"begin_at"] gives "2012-04-14T16:50:02Z"
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
SSS for milli seconds

iOS : Move forward dynamically NSDate with button

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

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