List of days in Objective C - objective-c

I wonder how could I make a list of days from MONDAY to SUNDAY...
I did it so:
- (NSString *) stringWithDayNameOf:(int)day {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"D"];
NSDate *date = [dateFormat dateFromString:[NSString stringWithFormat:#"%i", day]];
[dateFormat setDateFormat:#"eeee"];
NSString* outer = [dateFormat stringFromDate:date];
outer = [outer uppercaseString];
return outer;
}
for (int i = 1; i <= 7; i++) {
NSLog(#"DAY: %#", [self stringWithDayNameOf:i]);
}
But it displays days from today... How to fix that or make simpler?
Thanks!!

Use NSDateFormatter's weekdaySymbols and friends (for short names etc.)

%D is the format specifier for "day of year", not "day of week". There's no specifier for numerical day of week, since (as far as I know) no-one writes dates that way.
You need to create your date using NSDateComponents and then format that:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"eeee"];
NSCalendar * cal = [NSCalendar currentCalendar];
NSUInteger numWeekdays = [cal maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
NSDateComponents * comp = [[NSDateComponents alloc] init];
for( NSUInteger day = 1; day <= numWeekdays; day++ ){
[comp setWeekday:day];
[comp setWeek:0];
NSDate * date = [cal dateFromComponents:comp];
NSString * dayName = [dateFormat stringFromDate:date];
NSLog(#"%#", dayName);
}
Also, NSDateFormatter knows the names of the days of the week already: -[NSDateFormatter weekdaySymbols]. The first day of the week in the Gregorian calendar is Sunday.

Related

How to get all the date of last one month

i want to get all the dates from yesterday date to one month..
like today is 19 may, so i need all the date from 18 may to 18 April.
please help.
You can use this code.It works.
NSDate *currentDate = [NSDate date];
NSLog(#"Current Date = %#", currentDate);
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.month = -1;
NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(#"Date = %#", currentDatePlus1Month );
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *days = [[NSDateComponents alloc] init];
NSMutableArray* arr =[[NSMutableArray alloc]init];
NSInteger dayCount = 0;
while ( TRUE ) {
[days setDay: ++dayCount];
NSDate *date = [gregorianCalendar dateByAddingComponents: days toDate: currentDatePlus1Month options: 0];
if ( [date compare: currentDate] == NSOrderedAscending ){
[arr addObject:date];
}
if([[arr lastObject] isEqual:[currentDate dateByAddingTimeInterval:-60*60*24*1]])
{
NSLog(#"%lu",(unsigned long)arr.count);
break;
}
// Do something with date like add it to an array, etc.
}
if you find all dates you can remove count and get all dates in array.
To achieve this, I think you should have an Array holding all those dates. I'll write pseudocode about the logic here.
INIT dateArray
NSDate pastDate = (today).yesterday
NSDate lastMonth = pastDate.lastMonth()
WHILE pastDate > lastMonth // pastDate is after lastMonth
dateArray.add(pastDate)
pastDate = pastDate.yesterday
END WHILE
About how to turn this pseudocode into real code is another story (this would be quite long). Hope this help.
PS: If you'd like Objective-C solution, please comment. I'll take my time write it for you ;)

Converting a Gregorian date to Julian Day Count in Objective C

I need Objective C method for converting Gregorian date to Julian days same as this PHP method (GregorianToJD).
Precision: Incorporating time of day in Julian Date conversions
These Julian date conversion methods yield results identical to the U.S. Naval Observatory Online Julian Date Converter, which is more precise than NSDateFormatter's Julian Date conversion. Specifically, the functions below incorporate time-of-day (e.g. hour, minute and seconds), whereas NSDateFormatter rounds to noon GMT.
Swift examples:
func jdFromDate(date : NSDate) -> Double {
let JD_JAN_1_1970_0000GMT = 2440587.5
return JD_JAN_1_1970_0000GMT + date.timeIntervalSince1970 / 86400
}
func dateFromJd(jd : Double) -> NSDate {
let JD_JAN_1_1970_0000GMT = 2440587.5
return NSDate(timeIntervalSince1970: (jd - JD_JAN_1_1970_0000GMT) * 86400)
}
Objective-C examples:
double jdFromDate(NSDate *date) {
double JD_JAN_1_1970_0000GMT = 2440587.5;
return JD_JAN_1_1970_0000GMT + date.timeIntervalSince1970 / 86400;
}
NSDate dataFromJd(double jd) {
double JD_JAN_1_1970_0000GMT = 2440587.5;
return [[NSDate alloc] initWithTimeIntervalSince1970: (jd - JD_JAN_1_1970_0000GMT) * 86400)];
}
Note: Research confirms that the accepted answer rounds the date to a 24-hour interval because it uses the g format-specifier of NSDateFormatter, which returns the Modified Julian Day, according to the UNICODE standard's Date Format Patterns that Apple's date formatting APIs adhere to (according to the Date Formatting Guide).
According to http://en.wikipedia.org/wiki/Julian_day, the Julian day number for January 1, 2000, was 2,451,545. So you can compute the number of days between your date and this
reference date. For example (Jan 1, 2014):
NSUInteger julianDayFor01012000 = 2451545;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.year = 2014;
comp.month = 1;
comp.day = 1;
NSDate *date = [cal dateFromComponents:comp];
comp.year = 2000;
comp.month = 1;
comp.day = 1;
NSDate *ref = [cal dateFromComponents:comp];
NSDateComponents *diff = [cal components:NSDayCalendarUnit fromDate:ref toDate:date options:0];
NSInteger julianDays = diff.day + julianDayFor01012000;
NSLog(#"%ld", (long)julianDays);
// Output: 2456659
This gives the same result as http://www.php.net/manual/en/function.gregoriantojd.php:
<?php
$jd = GregorianToJD(1, 1, 2014);
echo "$jd\n";
?>
Inverse direction (Julian days to Gregorian year/month/day):
NSInteger julianDays = 2456659; // From above example
NSUInteger julianDayFor01012000 = 2451545;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.year = 2000;
comp.month = 1;
comp.day = 1;
NSDate *ref = [cal dateFromComponents:comp];
NSDateComponents *diff = [[NSDateComponents alloc] init];
diff.day = julianDays - julianDayFor01012000;
NSDate *date = [cal dateByAddingComponents:diff toDate:ref options:0];
comp = [cal components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:date];
NSLog(#"%04ld-%02ld-%02ld", (long)comp.year, (long)comp.month, (long)comp.day);
// Output: 2014-01-01
UPDATE: As Hot Licks correctly stated in a comment, it is easier to use a date
formatter with the "g" format:
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.year = 2014;
comp.month = 1;
comp.day = 1;
NSDate *date = [cal dateFromComponents:comp];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:#"g"];
NSInteger julianDays = [[fmt stringFromDate:date] integerValue];
NSLog(#"%ld", (long)julianDays);
// Output: 2456659
And for the inverse direction:
NSInteger julianDays = 2456659;
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:#"g"];
NSDate *date = [fmt dateFromString:[#(julianDays) stringValue]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [cal components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:date];
NSLog(#"%04ld-%02ld-%02ld", (long)comp.year, (long)comp.month, (long)comp.day);
// Output: 2014-01-01
let date = Date() // now
let cal = Calendar.current
var day = 0
day = cal.ordinality(of: .day, in: .year, for: date) ?? 0

How do i get first and last year of this decade in Objective-C?

How do i get first and last year of this decade ?
Can someone pls help me regarding this?
I can get 1st last date of this year, but what about this decade? here is my code
[dateFormat setDateFormat:#"yyyy"];
NSString *theDateFormatted = [dateFormat stringFromDate: Sdate];
theDateFormatted = [NSString stringWithFormat:#"%#%#", theDateFormatted, #"-01-01 12:00:00 AM"];
// set last of month
NSString *theDateFormattedE = [dateFormat stringFromDate: Sdate];
theDateFormattedE = [NSString stringWithFormat:#"%#%#", theDateFormattedE, #"-12-31 11:59:59 PM"];
[dateFormat setDateFormat:#"yyyy-MM-dd hh:mm:ss a"];
Edate = [dateFormat dateFromString:theDateFormattedE];
Sdate = [dateFormat dateFromString:theDateFormatted];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"DB Status" message: theDateFormattedE delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
First get the current year from the date, like so :
NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate]; // Get necessary date components
NSInteger year = [components year];
Then, to get the start year of the decade,
NSInteger firstYearOfTheDecade = year - (year % 10); //Add 1 to this if you want to start from x1
and for the last year
NSInteger lastYearOfTheDecade = firstYearOfTheDecade + 9;

adding current and future dates to an array

I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array.
NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc];
What would be the best way to go about storing the future dates?
NSMutableArray *days = [[NSMutableArray alloc] init];
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:tempCop];
for (int i = 0; i < 8; i++)
{
NSDateComponents *comps = [[NSDateComponents alloc]init];
[comps setDay:i];
[days addObject:[cal dateByAddingComponents:comps toDate:today options:0]];
}
NSMutableArray *days;
days = [[NSMutableArray alloc] init];
NSDate *todayDate = [NSDate Date];
[days addObject:todayDate];
for (int i = 1; i <= 6; i++)
{
NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*i];
[days addObject:newDate];
}
In this way, you can add days in array.
Take a look at dateByAddingTimeInterval: in the NSDate docs (link). It lets you add a given amount of seconds to a date.

Workout difference in months in Objective C

I would like to work out the difference in months
at the moment I have this code:
dateInterval = [endDate timeIntervalSinceDate:startDate];
But that returns a value in seconds, I would like to see the difference between the dates in months.
How would I do this?
Thanks
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *startDate = [inputFormatter dateFromString:#"07/03/2011"];
NSDate *endDate = [inputFormatter dateFromString:#"07/06/2011"];
NSInteger month_delta = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit fromDate: startDate toDate: endDate options: 0] month];
NSLog(#"---------------------------->>%d", month_delta);
[inputFormatter release]; // <-- in case not using ARC
it will log:
---------------------------->>3
You can create a NSDateComponents from the NSDates in question and just subtract the total months. (Total months = 12*year+currentMonth)
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDateComponents