I would like to compare the current date with another date, and if that is date is earlier than the current date, then I should stop the next action. How can I do this?
I have todays date in yyyy-MM-dd format. I need to check this condition
if([displaydate text]<currentdate)
{
//stop next action
}
Here if displaydate is less than todays date then it has to enter that condition.
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [dateFormatter dateWithString:#"xxxxxx"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:newDate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(#"today is less");
else if(result==NSOrderedDescending)
NSLog(#"newDate is less");
else
NSLog(#"Both dates are same");
got your solution from this answer How to compare two dates in Objective-C
Alternative to #NNitin Gohel's answer.
Compare using NSTimeInterval ie NSDate timeIntervalSince1970:
NSTimeInterval *todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval *previousTimeInterval = [previousdate timeIntervalSince1970];
if(previousTimeInterval < todayTimeInterval)
//prevous date is less than today
else if (previousTimeInterval == todayTimeInterval)
//both date are equal
else
//prevous date is greater than today
You can have a closer look at this Tutorial about NSDateFormatter and when you have your NSDate object you can compare it to another NSDate and get an NSTimeInterval which is the difference in seconds.
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
Some methods of NSDate class are:
isEarlierThanDate. // using this method you can find out the date is previous or not..
isLaterThanDate
minutesAfterDate.
minutesBeforeDate. etc..
also see this link with many methods of NSDate in iPhone SDK..
how-to-real-world-dates-with-the-iphone-sdk
Update
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
use this bellow method for convert NSString date to NSDate format just paste this method in your.m file
- (NSDate *)convertStringToDate:(NSString *) date {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd"];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", date);
date = [date stringByReplacingOccurrencesOfString:#"+0000" withString:#""];
nowDate = [formatter dateFromString:date];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", nowDate);
return nowDate;
}
after that when you want to use it just use like bellow..
NSDate *tempDate2 = [self convertStringToDate:yourStringDate];
and then try to compare like this..
if (tempDate2 > nowDate)
Related
I am trying to get the current time in NSDate format. I have been able to get the Unix timestamp to work, however, when I try to convert and format using an answer I found on SO, I get a null result. Would appreciate any suggestions on what I am doing wrong.
Would also be interested in any more direct way to get the current date time in date time format i.e.... something like 2015-09-04 00:55:25 +0000
- (NSDate *) timeStampDate {
//this returns time in string format
NSString *string = [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970] * 1000];
NSLog(#"string:%#",string);//this prints fine
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:string];
NSLog(#"date%#",date);//this prints null
return date;
/* this would go in opposite direction
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
string = [dateFormat stringFromDate:date];
*/
}
-(NSDate*) timeStampDate {
NSDate* currentDate = [NSDate date];
return [NSDate dateWithTimeInterval:
[[NSTimeZone defaultTimeZone] secondsFromGMTForDate: currentDate]
sinceDate: currentDate];
}
I have this date object from Parse, "2015-07-24 20:36:38 +0000" and I would like to compare it to today's date to see how much time has passed since the date on the date object. Any ideas how to do this?
I have this method I use to get the hour and minute, but I'm stuck on how to use this to compare dates outside of the current day.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm"];
NSString *formattedTime = [dateFormatter stringFromDate: date];
You can use an NSTimeInterval for this, the code is:
NSTimeInterval timeInterval = [date timeIntervalSinceNow];
with date being the date from parse as an NSDate, not NSString. and there should be no need to format it before comparing. Hope this helps
If you want this formatted as a string, in iOS 8 and later you can use NSDateComponentsFormatter:
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitHour;
NSString *string = [formatter stringFromDate:date toDate:[NSDate date]];
I am trying to find out whether current date is in between two given dates or not.First I coverted the two date into current date format i.e;2014-10-02 06:45:37 +0000
NSComparisonResult result,restult2;
NSString *startDateStr=#"10/04/2014 06:03 AM";
NSDateFormatter *startdf=[[NSDateFormatter alloc] init];
[startdf setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *startDate12=[startdf dateFromString:startDateStr];
NSString *startStr=[startdf stringFromDate:startDate12];
[startdf setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *startDate1=[startdf dateFromString:startStr]; //here startDate1 is nil
NSString *endDateStr=#"10/07/2014 03:03 AM";
NSDateFormatter *enddf=[[NSDateFormatter alloc] init];
[enddf setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *endDate12=[enddf dateFromString:endDateStr];
NSString *endStr=[enddf stringFromDate:endDate12];
[enddf setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *endDate1=[startdf dateFromString:endStr]; //here endDate1 is nil
NSDate *date = [NSDate date];
BOOL isBetween=[MyViewController date:date isBetweenDate:startDate1 andDate:endDate1];
if (isBetween)
{
NSLog(#"#####YES");
}
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
Please give any suggestions where I am going wrong.
Thanks in Advance...!
You are doing stuff in your code that is pretty much not doing anything. An NSDate object has no format. It has no time zone. It has no months, days, years. It is merely a point in time. When you then convert that date to a string you need to provide a format (which is what NSDateFormatter is for).
Change your code to something like this...
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSString *startDateStr = #"10/04/2014 06:03 AM";
NSDate *startDate = [dateFormatter dateFromString:startDateStr];
NSString *endDateStr = #"10/07/2014 03:03 AM";
NSDate *endDate = [dateFormatter dateFromString:endDateStr];
NSDate *date = [NSDate date];
// use a function name that matches the convention...
if ([MyViewController isDate:date betweenStartDate:startDate andEndDate:endDate])
{
NSLog(#"#####YES");
}
I think your function should be fine. Just don't mess around with the dates. Once you have them stop there and use them.
Obtain NSDate from your string and compare.
NSDate doesnt contain any format. It is just number of seconds. So you dont need to reconvert it multiple times, its error prone.
Also double check that dateFromString: method doesnt return nil.
To verify, whether a date falls into defined date range, you can use compare method or review the following code:
NSDate *now = [NSDate date];
NSDate *yesterday = [now dateByAddingTimeInterval:-1*24*60*60];
NSDate *tomorrow = [now dateByAddingTimeInterval:+1*24*60*60];
//first condition
if([now compare:yesterday] == NSOrderedDescending && [now compare:tomorrow] == NSOrderedAscending)
NSLog(#"now > yesterday and now < tomorrow");
else
NSLog(#"now is outside yesterday and tomorrow");
NSDate *weekAgo = [now dateByAddingTimeInterval:-7*24*60*60];
//second condition
if([weekAgo compare:yesterday] == NSOrderedDescending && [weekAgo compare:tomorrow] == NSOrderedAscending)
NSLog(#"weekAgo > yesterday and weekAgo < tomorrow");
else
NSLog(#"weekAgo is outside yesterday and tomorrow");
First condition results to
2014-10-02 14:45:21.791 dateTest[95595:8857503] now > yesterday and now < tomorrow
Second condition results to
2014-10-02 14:45:24.425 dateTest[95595:8857503] weekAgo is outside yesterday and tomorrow
convert both dates in milliseconds
long firstDate = [#(floor([startDate1 timeIntervalSince1970] * 1000)) longLongValue];
long secondDate = [#(floor([endDate1 timeIntervalSince1970] * 1000)) longLongValue];
and then covert also the date you want to check like this and check if that value is bigger than firstDate and smaller than `secondDate'
Comparing dates is quite complex. I have an app that is comparing opening and closing dates for stores and it works great for times in the same day, i.e. opening a 8am and closing at 5pm the same day.
Here is the code that compares the time:
if ([self timeCompare:openDate until:closeDate withNow:now]) {
NSLog(#"TIMECOMPARATOR = timeCompare>OPEN");
status = YES;
} else {
NSLog(#"TIMECOMPARATOR = timeCompare>CLOSED");
status = NO;
}
return status;
This calls the following method:
+(BOOL)timeCompare:(NSDate*)date1 until:(NSDate*)date2 withNow:(NSDate*)now{
NSLog(#"TIMECOMPARE = open:%# now:%# close:%#", date1, now, date2);
return ([date1 compare:now] == NSOrderedAscending && [date2 compare:now] == NSOrderedDescending);
}
The problem comes when the closing time is "assumed" by a person but of course not by a computer, to close at the next day, such as 7am to 2am. I obviously mean the next day. How do I accommodate for this to signal the computer to be the next day?
Compare the date's unix time. It will be accurate regardless of date as it is constantly increasing.
First you have to convert the strings "7:00 AM", "10:00 PM" to a NSDate from the current day. This can be done e.g. with the following method:
- (NSDate *)todaysDateFromAMPMString:(NSString *)time
{
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
// Get year-month-day for today:
[fmt setDateFormat:#"yyyy-MM-dd "];
NSString *todayString = [fmt stringFromDate:[NSDate date]];
// Append the given time:
NSString *todaysTime = [todayString stringByAppendingString:time];
// Convert date+time string back to NSDate:
[fmt setDateFormat:#"yyyy-MM-dd h:mma"];
NSDate *date = [fmt dateFromString:todaysTime];
return date;
}
Then you can proceed as in https://stackoverflow.com/a/20441330/1187415:
// Some example values:
NSString *strOpenTime = #"10:00 PM";
NSString *strCloseTime = #"2:00 AM";
NSDate *openTime = [self todaysDateFromAMPMString:strOpenTime];
NSDate *closeTime = [self todaysDateFromAMPMString:strCloseTime];
if ([closeTime compare:openTime] != NSOrderedDescending) {
// closeTime is less than or equal to openTime, so add one day:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setDay:1];
closeTime = [cal dateByAddingComponents:comp toDate:closeTime options:0];
}
NSDate *now = [NSDate date];
if ([now compare:openTime] != NSOrderedAscending &&
[now compare:closeTime] != NSOrderedDescending) {
// Shop is OPEN
} else {
// Shop is CLOSED
}
This is an app design question, not a coding question. You need to define a clear vocabulary for the user to communicate what they mean. I would suggest adding a UISwitch to the screen, with 2 positions on it: "Today" and "Tomorrow". You can add some program logic that takes a guess as to times where you think the user is talking about a date tomorrow, and set the default switch to the "tomorrow" state in that case, but the user should be able to tell you what they mean.
How about you just add a check whether all the three NSDate are having the same date (DDMMYYYY) value?
I have problems printing a date as NSString. I have stored current date and time at certain points of my app lifecycle this way:
NSDate *current = [NSDate date];
long currentTime = [current timeIntervalSince1970];
Now, I need to show those dates in UILabels. I tried this way:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:currentTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy - HH:mm:ss"];
NSString *stringFromDate = [formatter stringFromDate:date];
but I'm not getting the correct date nor the time. What could I be missing?
Thanks!
Try this,
NSString *stringFromDate=[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
also you can change the datestyle and timestyle.
Your currentTime variable is a long, and not an NSTimeInterval (a double). You are losing not only the fractional part (less important), but the upper range of the time interval. Change it to:
NSTimeInterval currentTime = [current timeIntervalSince1970];