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];
Related
Here's an example of what I want. The user may set up an alarm in my app for 1 minute in the future, so they can test it out. The time might be 19:23, so they'll set the alarm to 19:24, in which case I want it to be triggered on the next occurrence of 19:24 - in 1 minute's time.
If they set the alarm for 8am, I don't want it to set to 8am on the current day, but on the next occurrence of 8am - on following day.
How can I get it to aim for the next occurrence of the time chosen?
Assuming that the alarm time is given as "hour" and "minute", the following code
should produce the desired result:
NSDate *now = [NSDate date];
// Example values for testing:
NSUInteger alarmHour = 10;
NSUInteger alarmMinute = 5;
// Compute alarm time by replacing hour/minute of the current time
// with the given values:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:now];
[comp setHour:alarmHour];
[comp setMinute:alarmMinute];
NSDate *alarm = [cal dateFromComponents:comp];
// If alarm <= now ...
if ([alarm compare:now] != NSOrderedDescending) {
// ... add one day:
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];
alarm = [cal dateByAddingComponents:oneDay toDate:alarm options:0];
}
More tersely, what #HotLicks suggests:
NSDate *userEnteredDate;
NSDate *now = [NSDate date];
if (now == [now laterDate:userEnteredDate]) {
NSDateComponents *components = [[NSCalendar currentCalendar] components:255 fromDate:userEnteredDate]; // 255= the important component masks or'd together
components.day += 1;
userEnteredDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSDateFormatter *formatter_ = [[NSDateFormatter alloc]init];
NSDate *alarmDate = [formatter dateFromString:#"enter your users alarm time-examle(2345)"];
NSDate *currentDate = [NSDate date];
[formatter setDateFormat:#"HHmm"];
NSDate *finalDate;
if ([[formatter stringFromDate:currentDate] intValue] > [[formatter stringFromDate:alarmDate] intValue]) {
[formatter setDateFormat:#"HH:mm"];
[formatter_ setDateFormat:#"dd MM yyyy"];
NSDate *date = [currentDate dateByAddingTimeInterval:60*60*24*1];
finalDate = [formatter_ dateFromString:[NSString stringWithFormat:#"%# %#",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:date]]];
}else{
finalDate = [formatter_ dateFromString:[NSString stringWithFormat:#"%# %#",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:currentDate]]];
}
How will I compare current time [NSDate date] with fixed time 05:00:00 PM.
That 05:00 PM is already passed or not. I just need BOOL check for this.
- (BOOL)past5pm
{
NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorianCalender components:NSHourCalendarUnit fromDate:[NSDate date]];
if([components hour] >= 17) // NSDateComponents uses the 24 hours format in which 17 is 5pm
return YES;
return NO;
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH.mm"];
NSDate *currentDate = [NSDate date];
NSString *curDate = [dateFormatter stringFromDate:currentDate];
if ([curDate doubleValue] >= 17.00)
{
//set your bool
}
Try this
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate* date = [NSDate date];
//Get the string date
NSString* str = [dateFormatter stringFromDate:date];
NSDate *firstDate = [dateFormatter dateFromString:#"05:00:00 PM"];
NSDate *secondDate = [dateFormatter dateFromString:str];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSLog(#"Time Diff - %f",timeDifference);
You can probably use plain C style code and get the difference as an integer and then decide what you need to return from the comparison function depending on wether the difference is positive or negative. You can compare minutes this way as well. Dont forget to import time.h.
time_t now = time(NULL);
struct tm oldCTime;
localtime_r(&now, &oldCTime);
int hours = oldCTime.tm_hour;
int diff = 17-hours;
NSLog(#"Time difference is: %d.", diff);
I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.
Can anyone tell me how to do this..
Please also tell me the correct method to convert them back to NSDate.
Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.
NSString *dateStringA = #"2011-03-22";
NSString *dateStringB = #"2011-03-27";
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = #"yyyy-MM-dd";
NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates
NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
For string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];
for date to string
NSString *date = [[NSDate date] description];
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.
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.