I want to find a date by providing a weekday. For instance, I want to find the date of last Sunday and this Sunday. How to do it in iOS?
In OSX, NSDate provides a method of dateWithNaturalLanguageString, but iOS does not provide a similar method. Please help me.
Thanks.
you can calculate using NSDateComponents..
This is Sample. It helps you.
NSDate *date = [NSDate date];
NSString *dateString = [NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterLongStyle
timeStyle:NSDateFormatterNoStyle];
NSString *timeString = [NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterShortStyle];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
int weekday = [[currentCalendar components:NSWeekdayCalendarUnit fromDate:date] weekday];
NSString *weekdayString = [[[NSDateFormatter alloc] shortWeekdaySymbols] objectAtIndex:weekday-1];
Related
Here I'm trying to calculate the hours between two dates. When i run the application, it crashes. Could you please tell me the mistake in this code?
NSString *lastViewedString = #"2012-04-25 06:13:21 +0000";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss zzz"];
NSDate *lastViewed = [[dateFormatter dateFromString:lastViewedString] retain];
NSDate *now = [NSDate date];
NSLog(#"lastViewed: %#", lastViewed); //2012-04-25 06:13:21 +0000
NSLog(#"now: %#", now); //2012-04-25 07:00:30 +0000
NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:lastViewed];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
NSLog(#"hoursBetweenDates: %#", hoursBetweenDates);
Referring to this answer of a mostly similar question a better and Apple approved way would be using the NSCalendar methods like this:
- (NSInteger)hoursBetween:(NSDate *)firstDate and:(NSDate *)secondDate {
NSUInteger unitFlags = NSCalendarUnitHour;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:unitFlags fromDate:firstDate toDate:secondDate options:0];
return [components hour]+1;
}
If you target iOS 8 or later use NSCalendarIdentifierGregorian instead of the deprecated NSGregorianCalendar.
I think difference should be in int value...
NSLog(#"hoursBetweenDates: %d", hoursBetweenDates);
Hope, this will help you..
NSInteger can't be shown by using
NSLog(#"%#", hoursBetweenDates);
instead use:
NSLog(#"%d", hoursBetweenDates);
If unsure what to use look in the Apple Developer Docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265
I am facing a weird problem with NSDate, when I try fetch a date from device, sometimes it shows previous month for some versions
Here is my chunk of code for reference
NSDate *date = [NSDate date];
NSDateFormatter *dateF = [[NSDateFormatter alloc]init];
[dateF setDateFormat:#" dd.MM.yyyy "];
NSString *selectedDate = [dateF stringFromDate:date];
Any inputs are appreciated, Thank you
To avoid later localizing problems you might use NSCalendar and its method components:fromDate:
Something like this:
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
NSString * stringDate = [NSString stringWithFormat:#"%d.%d.%d", components.day, components.month, components.year];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"hh:mma dd/MMM"];
NSString *dateString = [dateFormat stringFromDate:today];
NSLog(#"date: %#", dateString);
[dateFormat release];
This is an example by Apple so it looks like you have your upper-case / lower-case right
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
Are you sure your device's date is set right? Also have you tried setting the locale of the NSDateFormatter?
EDIT:
To address you question in comments: NSDate is a point in time irrespective of time zones, calendars and so so on. NSCalendar and NSDateFormatter allow you to convert this point in time into a representation that is correct in a given time zone, with a given calendar.
I have three string
str1 = #"00:14";
str2 = #"00:55";
str3 = #"00:10";
i need to add the three string as a integer and display in the same time format
how can i do please help me
Thanks in Advance
Working with dates in Cocoa is fun! You could create a method like this:
- (NSDate *)dateByAddingDates:(NSArray *)dates {
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [dates objectAtIndex:0];
for (int i = 1; i < [dates count]; i++) {
NSDate *newDate = [dates objectAtIndex:i];
NSDateComponents *comps = [calendar components:unitFlags fromDate:newDate];
date = [calendar dateByAddingComponents:comps toDate:date options:0];
}
return date;
}
And use it like this:
NSString *str1 = #"00:14";
NSString *str2 = #"00:55";
NSString *str3 = #"00:10";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"mm:ss"];
NSArray *dates = [NSArray arrayWithObjects:[dateFormatter dateFromString:str1],
[dateFormatter dateFromString:str2],
[dateFormatter dateFromString:str3], nil];
NSDate *date = [self dateByAddingDates:dates];
NSLog(#"%#", [dateFormatter stringFromDate:date]);
To do things properly, it would be this:
Use an NSDateFormatter to convert the strings into NSDate objects.
Use [NSCalendar currentCalendar] to extract the NSDateComponents for each date, particularly the NSMinuteCalendarUnit.
Add up all the minutes of the date components, and set that into an NSDateComponent object
(optional) Use your calendar to convert the NSDateComponent back into an NSDate.
To do things stupidly, you'd get a substring of characters after :, invoke intValue on it to turn the string into an int, then add it all up. I don't recommend doing this, because it could lead to subtle and devious errors. Plus, there's already code in place to do it for you. :)
check out this related thread: Comparing dates
in summary, first parse the strings as NSDates using the initWithString: method call. Thereafter you can add and manipulate the dates any way you wish, and finally just format it for the right output.
Hope this hopes clarify your query.
Btw the Mac Developer SDK Reference can found here for your information:-
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDate
Im using an NSCalendar to display the week day, I have no problem displaying the weekday in an integer, but i am confused as to how i might get it to tell me the weekday, i.e. "Thursday." I read that %A, and %a might do the trick but I do not know how to implement them. My code is below.
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:now];
NSInteger weekday = [weekdayComponents weekday];
myLabel.text = [NSString stringWithFormat:#"%02d", weekday];
I use myLabel to display the string on the Iphone, but if there is a better way please let me know.
Thanks for the help.
James
To display day of week you actually need to use NSDateFormatter class, set 'EEEE' format to get full day name (like Thursday) or 'EEE' - for shortened (like Thu). Very sample code:
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"EEEE"];
NSLog([f stringFromDate:[NSDate date]]);
Can someone help me out with something.
I'm trying to get the current part of the day, am or pm. Is there an easy way of accomplishing this?
Thanks.
Sure, use NSDateFormatter:
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"a"];
NSLog ([formatter stringFromDate: now]);
[formatter release];
Outputs:
2009-08-06 14:20:35.538 yourApp [4971:20b] PM
Maybe there is an easier way .. but this works.
NSDate *now=[NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSHourCalendarUnit fromDate:now];
int hour = [components hour];
if ( hour > 12 ){
NSLog(#"PM %d",hour);
} else {
NSLog(#"AM");
}