how to find number of days [duplicate] - iphone

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
iPhone - get number of days between two dates
I am trying to compare 2 dates and find out the number of day in between them.
something like below:
now = [NSDate date];
// This is i am saving in NSUSerdefault on some condition,like
if (a == 1) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:MM:SS";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"The Current Time is %#",[dateFormatter stringFromDate:now]);
datesaved = [NSString stringWithFormat:#"%#",[dateFormatter stringFromDate:now]];
NSLog(#"old date saved : %#",datesaved);
[dateFormatter release];
}
and
find current date .
Now i want to compare current date with the date saved in NSUserDefaults to find number of day in between them.
ex:
The Current Time is 2012-12-16 19:12:74
old date saved : 2012-12-12
19:12:74
Number of days : 4
Thanks

NSDate *date1 = [NSDate dateWithString:#"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:#"2010-02-03 00:00:00 +0000"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(#"There are %d days in between the two dates.", numberOfDays);

You can take the day component of a date this way:
NSDate* now = [NSDate date]; // Or date from format
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* components = [cal components: NSDayCalendarUnit fromDate: now];
NSInteger day = [components day];
Do the same for the other date and compare them.

Related

NSDateComponent setHour is not setting correctly [duplicate]

This question already has an answer here:
sethours in NSDateComponents
(1 answer)
Closed 9 years ago.
I am trying to create a date with the time set to 12:00:01 am. Seconds and minutes set to their values correctly but the hour value always goes to whatever i set the value, + 4. Why 4? What is so special about that value? The minute and second values set to what I want correctly but it appears the hours value simply adds rather than replaces.
here is the code,
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:0];
[components setMinute:0];
[components setSecond:1];
NSDate *compareTime = [calendar dateFromComponents:components];
NSLog(#"compareTime: %#", compareTime);
NSLog(#"currentTime: %#", now);
output is :
compareTime: 2013-05-17 04:00:01 +0000
currentTime: 2013-05-17 15:00:37 +0000
EST is 4 hours ahead of GMT, hence your offset. Here's some code we use to create dates plus and minus the current time in the local time zone.
- (NSDate *) getDateWithHoursOffset : (int) aHourInt
{
CFGregorianDate gregorianStartDate, gregorianEndDate;
CFGregorianUnits startUnits = { 0,0,0, aHourInt,0,0 }; //2 hours before
CFGregorianUnits endUnits = { 0,0,0, 8,0,0 }; //5 hours ahead
CFTimeZoneRef timeZone = CFTimeZoneCopySystem();
gregorianStartDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeAddGregorianUnits(CFAbsoluteTimeGetCurrent(), timeZone, startUnits),timeZone);
gregorianStartDate.minute = 0;
gregorianStartDate.second = 0;
gregorianEndDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeAddGregorianUnits(CFAbsoluteTimeGetCurrent(), timeZone, endUnits),timeZone);
gregorianEndDate.minute = 0;
gregorianEndDate.second = 0;
NSDate* startDate = [NSDate dateWithTimeIntervalSinceReferenceDate:CFGregorianDateGetAbsoluteTime(gregorianStartDate, timeZone)];
CFRelease(timeZone);
return startDate;
}
NSDates exist independently of timezones. If you need the date to display 12:00:01 in the application, you should use a NSDateFormatter.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];
NSLog(#"formattedTime: %#", [dateFormatter stringFromDate:compareTime]);
This returns:
formattedTime: 12:00:01 AM Central Daylight Time
The problem is that your dates are correct but they're being logged in UTC relative to your device's time zone and that seems confusing. (It is, at first)
Your compare time is correct. It is set to midnight your time and outputted as UTC and if you're EST midnight would be 4am UTC:
compareTime: 2013-05-17 04:00:01 +0000
Current time is also correct, and again it is UTC time relative to your device's time zone:
currentTime: 2013-05-17 15:00:37 +0000
Your times are correct, its the output that is deceiving you.
This code (shamefully stolen from a thread listed below) should output compareTime's UTC date as 00:00:01 +0000. Though for date calculations UTC should be fine.
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:compareTime];
Here are a few S.O. threads to help further explain:
Does [NSDate date] return the local date and time?
Why isn't my time zone being saved into my NSDate?
NSDate is not returning my local Time zone /default time zone of device

How to get first date of MONTH, and first date of YEAR for a incoming date. in iPhone Objective c [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get all the days/dates in current week, this month, this year using the current date (today) in iPhone
I need to get the first day of Month, first day of Year for a date
(Most of times input date is current date [NSDate date])
could you please suggest how to get it,
E.G. todays current date = 3-MAY-2015
Output needed as follows:
First_Date_month = 1-MAY-2015
First_Date_year = 1-JAN-2015
Thanks in advance for your time
you can find the day month and year using NSDateComponents and can make NSDate as you want
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.currentDate = [calendar dateFromComponents:components];
int m = components.month;
int y = components.year;
int d = components.day;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy MM dd"];
NSDate *firstDateOfMonth = [df dateFromString:[NSString stringWithFormat:#"%# %# 01",y,m]];
NSDate *firstDateOfYear = [df dateFromString:[NSString stringWithFormat:#"%# 01 01",y]];

Convert String to Date and fetch the difference

hi i have 2 dates in string format
base_date_string = 10-12-01 12:00:00
current_date_string = 10-12-23 10:18:00
both the above values are in string
i want to get the number of days elapsed between these 2 dates
I tried to convert them to NSDate using NSDateFormatters and then getting the difference.
I realised that string does not properly converts to NSDate
when i convert to nsdate i got
base_date:::2010-12-01 06:30:00 +0000
current_date::::2010-12-23 04:48:19 +0000 (the time portion is not perfect)
Formatter class that i used is:
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
[formatter1 release];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter2 release];
//subrtrcation of basedate from current date to get elapsed number of days
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *diff = [calendar components:(NSDayCalendarUnit)
fromDate:base_date toDate:current_date options:0];
int date_value = [diff day];
Please any help is appreciated
30 seconds in the NSDate documentation revealed:
-[NSDate timeIntervalSinceDate:]
So using the dates in your question...
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
difference = fabs(difference);
NSLog(#"there are %f seconds between %# and %#", difference, current_date, base_date);
edit
ok, so the problem is not date differencing. You're observing that the string you're inputting is 5 and 1/2 hours ahead of the date you're getting back.
Well, let's look at this. The date returned is in GMT time (as denoted by the +0000). 5 and 1/2 hours ahead of that is the timezone used in India. So. Are you in India? If you are, then this is just a matter of needing to -setTimezone: on your NSDateFormatter.
You can use this code of function to get the difference between 2 dates
-(int)howManyDaysHavePast:(NSDate*)lastDate :(NSDate*)today {
NSDate *startDate = lastDate;
NSDate *endDate = today;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
[gregorian release];
int days = [components day];
return days;
}
hAPPY iCODING...
Use the following code
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter1 release];
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
Then you will get difference in number of seconds. Then you can get in number of days as following
float days = difference/86400;
The "days" consists the number of days that the current_date is differ from the base_date.

calculate calendar week

how can I calculate the calendar week? A year has 52/53 weeks and there are two rules:
-USA
-DIN 1355 / ISO 8601
I'd like to work with DIN 1355 / ISO 8601. How can I manage that?
Edit:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"ww"];
NSString *weeknumber = [dateFormat stringFromDate: today];
NSLog(#"week: %#", weeknumber);
Taken from http://iosdevelopertips.com/cocoa/date-formatter-examples.html
Where do I find the allowed date formats?
Use an NSCalendar and NSDateComponents.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSWeekCalendarUnit fromDate:date];
NSInteger week = [components week];
Or use:
CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
CFTimeZoneRef currentTimeZone = CFTimeZoneCopyDefault();
SInt32 weekNumber = CFAbsoluteTimeGetWeekOfYear(currentTime, currentTimeZone);
The numbering follows the ISO 8601 definition of week.
NSDate *today = [NSDate date];
NSCalendar *ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
ISO8601.firstWeekday = 2; // Sunday = 1, Saturday = 7
ISO8601.minimumDaysInFirstWeek = 4;
NSDateComponents *components = [ISO8601 components:NSCalendarUnitWeekOfYear fromDate:today];
NSUInteger weekOfYear = [components weekOfYear];
NSDate *mondaysDate = nil;
[ISO8601 rangeOfUnit:NSCalendarUnitYearForWeekOfYear startDate:&mondaysDate interval:NULL forDate:today];
NSLog(#"The current Weeknumber of Year %ld ", weekOfYear);
You should user NSDateFormatter like so:
NSDateFormatter *fm = [[NSDateFormatter alloc] initWithDateFormat:#"ww" allowNaturalLanguage:NO];
NSString *week = [fm stringFromDate: date];
There is many kinds of Canlendar.
Week number according to the ISO-8601 standard, weeks starting on Monday. The first week of the year is the week that contains that year's first Thursday (='First 4-day week'). The highest week number in a year is either 52 or 53. This year has 52 weeks.This is not the only week numbering system in the world, other systems use weeks starting on Sunday (US) or Saturday (Islamic).
More details: http://www.epochconverter.com/weeknumbers
And Apple does support that, so you could find correct way referred from https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/
For example, with ISO-8601 standard:
NSCalendar *ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
Hope this could help.

How to find last day of week in iPhone?

In my application I'm using following codes to retrieve current date and day :-
NSDate *today1 = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:#"dd/MM/yyyy :EEEE"]; NSString *dateString11 = [dateFormat stringFromDate:today1];
NSLog(#"date: %#", dateString11);
//[dateFormat release];
NSCalendar *gregorian11 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSDateComponents *components1 = [gregorian11 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today1];
[components1 setDay:([components1 day]-([components1 weekday]-1))];
NSDate *beginningOfWeek1 = [gregorian11 dateFromComponents:components1];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"dd/MM/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_first stringFromDate:beginningOfWeek1];
NSLog(#"First_date: %#", dateString_first);
[components1 setDay:([components1 day]-([components1 weekday]-1) + 6)]; now =[gregorian dateFromComponents:components1]; [format setDateFormat:#"dd/MM/yyyy :EEEE"]; dateString = [format stringFromDate:now]; NSLog(#" week Last_date: %#", dateString);
but using above code I only got the current day and Date and first day of week but I need to get last day of week. But it gives the wrong output. Where am I wrong in my code and what modification is needed to get last day/date of week?
When you call setDay: you are sometimes setting it to a negative day. I don't know if setDay and/or dateFromComponents: will handle that.
To create a NSDate for a date/time that is in the past (or future) you can subtract (or add) the number of seconds that you want to go back (or forward), like this:
// convert to seconds
NSTimeInterval tmpSecs = [[NSDate date] timeIntervalSinceReferenceDate];
// Shift the date/time (in seconds) to a new date X days away:
tmpSecs += daysOffset * 86400; // 86400 seconds per day
// convert back to NSDate and return the result
return [NSDate dateWithTimeIntervalSinceReferenceDate:tmpSecs];