convert string into NSDate - iphone

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];

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);

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];
}

how to take a date without time in iphone

I am try to remove time from date how to do this i try this code it not working proper where i am wrong
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *todaysDate = [NSDate date];
//NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSDateComponents*dateComponents = [gregorian components:NSDayCalendarUnit fromDate:todaysDate];
[dateComponents setDay:1];
app.selectionData.fromDateSelected = [gregorian dateByAddingComponents:dateComponents toDate:todaysDate options:0];
//[dateComponents release];
[gregorian release];
Are you trying to do this?
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int comps = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:comps fromDate:[NSDate date]];
[dateComponents setDay:[dateComponents day] + 1];
app.selectionData.fromDateSelected = [gregorian dateFromComponents:dateComponents];
[gregorian release];
To only get the date, you can use NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString* currentDate = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
You can also supply your own format for the date.
For ex:
[dateFormattter setDateFormat:#"yyyy-mm-dd"];
You can refer to UTS #35 and Date Formatting Guide for more options on formatting.
Try this out. This works for me
NSDate *todaysDate = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSString *stringDate = [dateFormat stringFromDate:todaysDate];
NSLog(#"stringDate: %#",stringDate);
[dateFormat release];
EDIT:
NSDate *today = [NSDate date];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *date = [today addTimeInterval:secondsPerDay];
//Change NSDate *date = [tomorrow addTimeInterval:-secondsPerDay]; for yesterday
NSDate *tomorrow = date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSString *stringDate = [dateFormat stringFromDate:tomorrow];
NSLog(#"stringDate: %#",stringDate);
[dateFormat release];
Hope this helps you.

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