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.
Related
I am working on a project where i need to set an alarm on 7 days before particular date the user has selected from date picker.
I used the following code to get the date from user
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterFullStyle];
NSString *dateStr = [NSString stringWithFormat:#"%#",[df stringFromDate:datePickerObj.date]];
[df release];
Can any one please tell me how to get the date of 7 days previous to the selected date.
Thanks in advance
Use dateByAddingComponents:toDate:options:, like this:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = -7;
NSDate *earlierDate = [calendar dateByAddingComponents:components
toDate:datePickerObj.date options:0];
Is there a way to subtract the current date by 5. say if today is 2008-12-9 i need to get the date 5 days back. If we output this, the date should display as 2008-12-4.
How can i code this programatically? or a tutorial that would help
Always use NSCalendar and NSDateComponents for date calculations. This will take into account oddities like leap years with 29 days in February, leap seconds and daylight saving changes.
NSDate *date = [NSDate date]; // Using current date here
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = - 5; // Find date for 5 days ago
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
Use NSDateComponents
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
[offsetComponents setDays:-5];
NSDate *fiveDaysAgo = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
to convert it to a string with the preferred format, use NSDateFormatter
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *formattedDateString = [dateFormatter stringFromDate:fiveDaysAgo];
This is the brute-force way:
Sustract 5 from DAY.
If DAY < 0, add number of days of the previous month and sustract 1 from MONTH.
If MONTH < 0, add number of month of a year and sustract 1 from YEAR.
The advantage of the brute-force approach is that it will work with every language.
#define SOME_HOUR -24*5
NSDate *today = [NSDate date];
NSDate *someDay = [NSDate dateWithTimeInterval:60*60*SOME_HOUR sinceDate:today];
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.
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];
I'm looking to get the current hour and minute on a user's iPhone for display in an app that doesn't show the status bar. Is there a simple way to do this?
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
NSLog(#"User's current time in their preference format:%#",currentTime);
-(void)currentTime
{
//Get current time
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
NSInteger hour = [dateComponents hour];
NSString *am_OR_pm=#"AM";
if (hour>12)
{
hour=hour%12;
am_OR_pm = #"PM";
}
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
NSLog(#"Current Time %#",[NSString stringWithFormat:#"%02ld:%02ld:%02ld %#", (long)hour, (long)minute, (long)second,am_OR_pm]);
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]]
[dateFormatter release]; dateFormatter = nil;
I think you should try this. The timeZone is important.
See this similar question for an answer. You will have to change it to your date format.
[[NSDate date] timeIntervalSince1970];
if you are looking to calculate time intervals, you are better off using CACurrentMediaTime
double currentTime = CACurrentMediaTime();
A shorter approach
NSDate * now = [NSDate date];
timeLabel.text = [NSDateFormatter localizedStringFromDate:now
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterShortStyle];
CFAbsoluteTimeGetCurrent()
Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.