Breaking Up a String in Objective-C - objective-c

All,
I have a method that takes a date (YYYY-MM-DD H:M:S) from the database and creates a URL with the year, month and day components from the date string. My solution works but I was wondering if there is a better way to do this? How are the cool kids doing it? :-)
Thanks!
-(NSString *) prettyURLFrom:(NSString *)dateString{
NSString * URLString = #"";
NSString *URL = #"http://www.theblues.com/featured/article/";
NSArray *myWords = [dateString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"-\" \" :"]
];
URLString = [NSString stringWithFormat:#"%#%#/%#/%#",
URL,
[myWords objectAtIndex:1],
[myWords objectAtIndex:2],
[myWords objectAtIndex:0]];
return URLString;
}

Like I said in the comments, I find it bizarre you're passing and returning values as strings when they probably should be NSDate and NSURL respectively.
I would probably do something like:
-(NSURL*)URLFromDate:(NSDate*)date
{
// Assumes user uses a gregorian calendar
NSDateComponents *dateComp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
return [NSURL URLWithString:[NSString stringWithFormat:#"http://www.theblues.com/featured/article/%li/%li/%li"
, [dateComp year]
, [dateComp month]
, [dateComp day]]];
}

If you have NSDate object then you can use
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSString to NSDate
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-DD HH:MM:SS"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:#"1999-07-02 2:2:4"];

Related

How to calculate different between two NSDate variable?

I am building an IOS application where I am doing following step.
Parsing the data.
Getting OpenTime and CloseTime.
Set the OpenTime and CloseTime in a NSString variable name as openTime and closeTime.
Now the problem is I want to calculate the different of this two time.
I am getting the value like,
OpenTime = "00:15:00" and CloseTime = "1:30:00"
The Time formate is - 24 hours.
Can someone help me in solving this problem I am new in IOS.
Let say you have two NSDate variables openTime and closeTime
int calendarUnit = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:calendarUnit fromDate: openTime toDate: closeTime options:0];
int months = [components month];
int days = [components day];
int hours = [components hour];
int minutes = [components minute];
You can use NSDateComponents
NSDate *date = [self getTimeInDateFormatFromString://your time string]; // your method return nsdate from string using nsformatter
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comp = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
you can use comp.hour and minute to get time difference.
NSString *openTime = #"12:48:00";
NSString *closingTime = #"21:52:00";
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"hh:mm:ss"];
NSDate *openDate = [formatter dateFromString:openTime];
NSDate *closeDate = [formatter dateFromString:closingTime];
int calendarUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [[NSCalendar currentCalendar] components:calendarUnits fromDate: openDate toDate: closeDate options:0];
NSLog(#"The difference is: %ld hours , %ld minutes, %ld seconds", (long)components.hour, (long)components.minute, (long)components.second);
-(void)compareTwoDate:(NSDate *)start :(NSDate *)end
{
NSDate *end_date =end;
NSDate *startDate =start;
NSTimeInterval distanceBetweenDates = [startDate timeIntervalSinceDate:end_date];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
}
NSArray *star_array=[#"00:15:00" componentsSeparatedByString:#":"];
NSInteger start_time=[[star_array objectAtIndex:2] integerValue]*3600+[[star_array objectAtIndex:1] integerValue]*60+[[star_array objectAtIndex:0] integerValue];
NSArray *end_array=[#"1:30:00" componentsSeparatedByString:#":"];
NSInteger end_time=[[end_array objectAtIndex:2] integerValue]*3600+[[end_array objectAtIndex:1] integerValue]*60+[[end_array objectAtIndex:0] integerValue];
NSInteger diff_seconds=end_time-start_time;

Convert NSString to NSDate and timeZone?

Ive been racking my brains with no luck. Could someone please tell my how i would convert this string:
NSString *dateTimeStr =[[self.responseArray objectAtIndex:indexPath.row]objectForKey:#"date_time"];
2014-04-13T17:00:00+11:0
into a NSDate? and time format ?
how can i covert this date into time format ?
here is my code:
NSString *dateTimeStr =[[self.responseArray objectAtIndex:indexPath.row]objectForKey:#"date_time"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:#"yyyy-MM-ddHH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:dateTimeStr];
NSLog(#"date %#", date);
NSTimeInterval seconds = [date timeIntervalSinceReferenceDate];
in console
NSLog(#"seconds==> %f", seconds);
i have time in miliseconds then how can i take out minutes/hours/ ?
NSString *dateString = #"2014-04-13T17:00:00+11:00";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSDateComponents *dateComponents = [[NSCalendar currentCalendar]
components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];

add current day with one day after and one day before to date picker objective-C

I have a datepicker and I want to have just one row with 3 options: current day, one day after and one day before .
Would you help me to do that?
My question is, how can I add 'current day' with one day after and one day before ?
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:days];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *end = [gregorian dateByAddingComponents:components toDate:[NSDate date] options:0];
Where days is an integer representing the days you want to add/subtract from the current day.
This is how i did-
-(void)getDate{
NSString *str_CurDate =[self getCurrentDate];
NSString *str_NextDay =[self getFormattedDate:[self dateByAddingDays:1]];
NSString *str_PrevDay =[self getFormattedDate:[self dateByAddingDays:-1]];
}
Now implement these method
-(NSString*)getCurrentDate{
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"d/M/yyyy"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
return dateString;
}
- (NSDate *) dateByAddingDays:(int)days {
NSDate *retVal;
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:days];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
retVal= [gregorian dateByAddingComponents:components toDate:[NSDate date] options:0];
return retVal;
}
-(NSString*)getFormattedDate:(NSDate*)myDate{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"d/M/yyyy"];
NSString *dateString = [dateFormatter stringFromDate:myDate];
return dateString;
}
Encapsulate in a category on NSDate
- (NSDate *) dateByAddingDays:(int)days {
NSDate *retVal;
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:days];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
retVal = [gregorian dateByAddingComponents:components toDate:self options:0];
return retVal;
}

How can i find the time difference in this code correctly?

I am trying to compare the current time to the time 10:15 and then find the difference ie. the minutes left until 10:15. Everything compiles, but I always get 75....Can someone help?? I would really love coding examples if at all possible. Also I tried to use -(time interval)timeIntervalSinceNow, but I couldnt figure out how to work it, so if anyone has an explanation for that too, i would be extremely grateful
*Note i am using Version 3.2.6, please advise accordingly, thanks
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =
[gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
NSInteger combo = hour + (minute/60) + (second/3600);
NSTimeInterval time = combo*60*60;
NSTimeInterval tenFifteenFirstPeriodStop = 10.25*60*60;
double myDouble;
int myInt;
NSString* myNewString;
NSString *info;
if(time <tenFifteenFirstPeriodStop){
myDouble = (tenFifteenFirstPeriodStop-time)/60;
myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5));
myNewString = [NSString stringWithFormat:#"%d", myInt];
info = [[NSString alloc] initWithFormat:
#"%#",myNewString];
}
NSString *message = [[NSString alloc] initWithFormat:
#"%#", info];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Minutes Until the Bell Rings" message:message delegate:nil cancelButtonTitle:#"Great!" otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
This will give you the time in seconds till 10.15 today. If it has passed already, it will show the time in seconds to 10.15 tomorrow.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:today];
[components setMinute:15];
[components setHour:10];
NSDate * tenFifteenToday = [gregorian dateFromComponents:components];
if ( [tenFifteenToday timeIntervalSinceNow] < 0 ) {
NSDateComponents * daysToAdd = [[[NSDateComponents alloc] init] autorelease];
[daysToAdd setDay:1];
NSDate * tenFifteenTomorrow = [gregorian dateByAddingComponents:daysToAdd toDate:tenFifteenToday options:0];
NSLog(#"%.0lf", [tenFifteenTomorrow timeIntervalSinceNow]);
} else {
NSLog(#"%.0lf", [tenFifteenToday timeIntervalSinceNow]);
}

Combing NSString with the day of week and NSDate with the time into an NSDate object

I have the following two objects:
An NSString object with a day of the week, ie Monday, Tuesday, Wednesday, etc.
An NSDate object that was saved from a UIDatePicker with UIDatePickerModeTime.
I need to create a third object, NSDate that is the next occurance of the NSString with the time from the NSDate.
//Ex. Tuesday
NSString *confessOn = [[NSUserDefaults standardUserDefaults] objectForKey:kRemindToConfessOn];
//Ex. 2011-02-11 20:13:19
NSDate *confessAt = [[NSUserDefaults standardUserDefaults] objectForKey:kRemindToConfessAt];
NSDate *fireDate = //should be an NSDate with the value 2011-02-15 20:13:19
NSDateFormatter * df = [[[NSDateFormatter alloc] init] autorelease];
[df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier(#"en")] autorelease];
[df setDateFormat:#"EEEE"];
NSDate *confessOnDate = [df dateFromString:confessOn];
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *confessOnComps = [cal components:NSWeekdayCalendarUnit fromDate:confessOnDate];
NSDateComponents *confessAtComps = [cal components:NSWeekdayCalendarUnit fromDate:confessAt];
NSInteger weekdayDifference = ([confessOnComps weekday] + 7 - [confessAtComps weekday]) % 7;
NSDate *fireDate = [confessAt dateByAddingTimeInterval:weekdayDifference * 86400];