This question already has an answer here:
Compare current time with two times-of-day strings [closed]
(1 answer)
Closed 8 years ago.
I want to compare current time with two different times on different dates.MY code is
NSString *time1 = record.trigger_from_time;
NSString *time2 = record.trigger_to_time;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSLog(#"%#,%#",date1,date2);
I'm getting log as 2000-01-01 09:12:00 +0000,2000-01-01 12:30:00 +0000
But MY current time is 2014-04-01 17:06:18.
I'm getting current date from
NSDate *now = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.dateFormat = #"HH:mm";
[timeFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"The Current Time is %#",[timeFormatter stringFromDate:now]);
I want to compare thie current time with record.trigger_from_time and record.trigger_to_time
NSString *time1 = #"09:10:02";
NSString *time2 = #"17:10:16";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:"];
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
NSLog(#"time1 is later than time2");
}
else if(result == NSOrderedAscending)
{
NSLog(#"time2 is later than time1");
}
else
{
NSLog(#"time1 is equal to time2");
}
Comparing 2 NSDates.
...
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
if ([date2 compare:date1] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([date2 compare:date1] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
UPD:
via Switch
...
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSComparisonResult result = [date2 compare:date1];
switch(result){
case NSOrderedDescending:
NSLog(#"date1 is later than date2");
break;
case NSOrderedAscending:
NSLog(#"date1 is earlier than date2");
break;
default:
NSLog(#"dates are the same");
break;
}
Related
compare 2 dates
if (from_date >= today && totime < = today)
i tried with this
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
NSString * TodayDate = [dateFormatter stringFromDate:[NSDate date]];
if ([displayList.fromTime compare:TodayDate] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([displayList.toTime compare:date2] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
You can comparing NSString, which is wrong. You need to compare two NSDate objects.
Here is update code:
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
// You are doing wrong compareing at here. You need to compare Date nor sting.
// NSString * TodayDate = [dateFormatter stringFromDate:[NSDate date]];
NSDate *TodayDate = [NSDate date];
NSDate *compareData = [dateFormatter dateFromString:#"2017-07-09 11:12:11"];
if ([compareData compare:TodayDate] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([compareData compare:TodayDate] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
You're not saying what class of object fromDate is, but since you're comparing it to TodayDate, which is a string, I'm assuming all of your dates are strings when you compare them? If so, that's a bad choice. Date comparison and string comparison are not the same and will yield different results.
Instead of turning today's date into a string, you should turn fromDate into an NSDate, and then compare those.
If, OTOH, fromDate is not a string, then that's your error. Just because two objects result in the same text being NSLogged doesn't mean they're the same type and can be compared, so make sure they're all the same type (NSDate) and then compare those.
This question already has answers here:
How to Check if an NSDate occurs between two other NSDates
(10 answers)
Closed 6 years ago.
I have to check my current date time is in between the given 2 set of date time (need to check both time and date part of NSDate).
Here is my code
NSString *startingDate = [[[vehicle timeRestrictions] objectAtIndex:i] valueForKey:#"start_ts"];
NSString *endingDate = [[[vehicle timeRestrictions] objectAtIndex:i] valueForKey:#"end_ts"];
NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[startingDate longLongValue]/1000];
NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:[endingDate longLongValue]/1000];
NSLog(#"Start Date %#",startDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss a"]; // here replace your format dd.MM.yyyy
NSLog(#"result: %#", [dateFormatter stringFromDate:[NSDate date]]);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:#"YYYY-MM-dd\'T\'HH:mm:ss ssZZZZZ"];
[dateFormat setDateFormat:#"dd-MM-yyyy HH:mm:ss "];
BOOL checkVehicleRestriction = [self getDatePartForRestriction:[dateFormat stringFromDate:startDate] :[dateFormat stringFromDate:endDate]];
-(BOOL)getDatePartForRestriction:(NSString *)date :(NSString *)endDate{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd\'T\'HH:mm:ssZZZZZ"];
[dateFormat setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSLog(#"%# - %#",date,endDate);
if([self isDate:[NSDate date] inRangeFirstDate:[dateFormat dateFromString:date] lastDate:[dateFormat dateFromString:endDate]]){
return YES;
}
return NO;
}
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
return !([date compare:firstDate] == NSOrderedAscending) && !([date compare:lastDate] == NSOrderedDescending);
}
When I run this code i am always getting YES for checkVehicleRestriction .
These are the date time format am using 02-06-2016 20:09:47 PM
I'm not sure how you are calculating your startDate and end Date, but to simply calculate if your current date is in between two dates or not, you can do this:
Get the dates:
NSString *startingDate = #"01-06-2016 20:09:47 PM";
NSString *endingDate = #"08-06-2016 20:09:47 PM";
NSDateFormatter *startForm=[[NSDateFormatter alloc]init];
[startForm setDateFormat:#"dd-MM-yyyy HH:mm:ss a"];
NSDate *startDate = [startForm dateFromString:startingDate];
NSDate *endDate = [startForm dateFromString:endingDate];
and to check if current date is in between two dates
Date1(before current) CurrentDate Date2(after current) = CurrentDate is in Range
Date2(before current) CurrentDate Date1(after current) = CurrentDate is in Range
So we need to check for only two cases
case A - (startDateIsOld && !endDateIsOld)
case B- (!startDateIsOld && endDateIsOld)
In these both cases the current date is said to be in range .
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
BOOL startDateIsOld = false;
BOOL endDateIsOld = false;
if ([date compare:firstDate]==NSOrderedAscending) {
NSLog(#"first date is after current date");
startDateIsOld=NO;
}
if ([date compare:lastDate]==NSOrderedDescending){
NSLog(#"last date is before current date");
endDateIsOld=YES;
}
if ([date compare:firstDate]==NSOrderedDescending) {
NSLog(#"first date is before current date");
startDateIsOld=YES;
}
if ([date compare:lastDate]==NSOrderedAscending){
NSLog(#"last date is after current date");
endDateIsOld=NO;
}
if ((startDateIsOld && !endDateIsOld) || (!startDateIsOld && endDateIsOld) ) {
NSLog(#"date is in range");
return YES;
}
return NO;
}
TO simplify this method you can just do:
if ((([date compare:firstDate]==NSOrderedDescending) && ([date compare:lastDate]==NSOrderedAscending)) || (([date compare:firstDate]==NSOrderedAscending) && ([date compare:lastDate]==NSOrderedDescending))) {
NSLog(#"date is in range");
return YES;
}
I'm getting the date string from server in 01/02/2014 16:43:00 AM format, which is having GMT timeZone.
I've to compare that date with current date for live streaming. If the current date is lesser than that server date I've to show some alert which shows the correct live starting time. But I'm not able to compare them.
How to convert that server date string to date format and how to compare that date with current date ?
I'm using the following code :
NSString *DateFromServer = video.Eventutcstart;
NSDateFormatter * dateFormatter1 = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
[dateFormatter1 setTimeZone:[NSTimeZone timeZoneWithName:tzName]];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];
NSString *str = [dateFormatter1 stringFromDate:[NSDate date]];
NSDate *currentDate = [dateFormatter1 dateFromString:str];
NSDate *serverDate = [dateFormatter1 dateFromString: DateFromServer];
NSLog(#"currentDate %#", currentDate);
NSLog(#"serverDate %#", serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
output:
2014-01-03 11:30:25.346 VMS[955:70b] currentDate 2014-01-02 19:00:23 +0000
2014-01-03 11:30:32.088 VMS[955:70b] serverDate 2014-01-02 19:00:46 +0000
Please help me to solve this....
Please use below code. You were not setting timezone correctly:
NSString *DateFromServer = video.Eventutcstart;
NSDateFormatter * dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];
NSString *str = [dateFormatter1 stringFromDate:[NSDate date]];
NSDate *currentDate = [dateFormatter1 dateFromString:str];
NSDate *serverDate = [dateFormatter1 dateFromString: DateFromServer];
NSLog(#"currentDate %#", currentDate);
NSLog(#"serverDate %#", serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
For date comparison only,
You have two dates correctly obtained so can use :
int days1 = [currentDate timeIntervalSince1970] / 86400;
int days2 = [serverDate timeIntervalSince1970] / 86400;
if(days1==days2)
{
//do something;
}
else
{
//do something
}
Above code does not takes time in consideration and compares only year/month/day
For NSdate time comparison
unsigned int flags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* component1 = [calendar components:flags fromDate:currentDate];
NSDateComponents* component2 = [calendar components:flags fromDate:serverDate];
NSDate* currentDateTimeOnly = [calendar dateFromComponents:component1];
NSDate* serverDateTimeOnly = [calendar dateFromComponents:component2];
NSComparisonResult result;
result = [currentDateTimeOnly compare:serverDateTimeOnly];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
try this code
if(result == NSOrderedAscending)
{
NSLog(#"alert message");
}
instead of this one
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
if you want to check both constraint with both date then you can use bellow code.
if(result == NSOrderedAscending){
NSLog(#"serverDate is in the future");
}else if(result == NSOrderedDescending){
NSLog(#"serverDate is in the past");
}else{
NSLog(#"Both dates are the same");
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString *a1=[def objectForKey:#"Currentdate"];
NSDate *now = [dateFormat dateFromString:a1];
NSDate * currentdate = [NSDate date];
NSString *nowstr=[dateFormat stringFromDate:currentdate];
NSDate *todaydate=[dateFormat dateFromString:nowstr];
NSLog(#"Now is %# and current date is %#",[def objectForKey:#"Currentdate"],nowstr);
NSComparisonResult result = [todaydate compare:now];
switch (result)
{
case NSOrderedAscending:
dateiswhich=-1;
NSLog(#"%# is in future from %#", currentdate, now);
break;
case NSOrderedDescending:
dateiswhich=1;
NSLog(#"%# is in past from %#", currentdate, now);
break;
case NSOrderedSame: dateiswhich=-1;
break;
default: NSLog(#"erorr dates %#, %#", currentdate, now); break;
}
use above code might be useful to you
This question already has answers here:
How to compare two NSDates: Which is more recent?
(13 answers)
Closed 9 years ago.
I got to two date string in 24 Hours format how to compare ? For example
The current date :2013-06-27 13:51
The server date :2013-06-27 11:51
The current date cannot greater than the server date.Please help
Here is the datepicker
NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
[datePickerFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
self.myCurrentDate = [datePickerFormat stringFromDate:self.myDatePicker.date];
NSDate *myDate = [datePickerFormat dateFromString:self.myCurrentDate];
I not able to convert it to 24 hours format, and final datetime show is incorrect.
Try this,
// The current date :2013-06-27 13:51
// The server date :2013-06-27 11:51
NSString *strCurrentDate = #"2013-06-27 13:51";
NSString *strServerDate =#"2013-06-27 11:51";
NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
[datePickerFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *currentDate = [datePickerFormat dateFromString:strCurrentDate];
NSDate *serverDate = [datePickerFormat dateFromString:strServerDate];
NSLog(#"date %#",currentDate);
NSLog(#"date %#",serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"current date is less");
else if(result == NSOrderedDescending)
NSLog(#"server date is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same");
else
NSLog(#"Date cannot be compared");
Try this class utility:
.h
#import <Foundation/Foundation.h>
#interface NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
#end
.m
#import "NSDate+Compare.h"
#implementation NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedAscending);
}
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
return ([self compare:date] == NSOrderedDescending);
}
-(BOOL) isEarlierThan:(NSDate*)date {
return ([self compare:date] == NSOrderedAscending);
}
#end
Try this code for any comparison between dates... You should not compare date in the form of string. Compare the dates before conversion to string. Convert the self.serverDate into date format using dateFromString function of the formatter by specifying the exact date format as that of the dateString. Then compare the dates using following function.
NSDate *today = [NSDate date]; // current date
NSDate *newDate = self.serverDate; // other date
NSComparisonResult result;
result = [today compare:newDate]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"today is less");
else if(result == NSOrderedDescending)
NSLog(#"newDate is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same");
else
NSLog(#"Date cannot be compared");
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date1 = [dateFormatter dateFromString:TodatDate];
NSDateFormatter *dateFormatte = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatte setDateFormat:#"yyyy-MM-dd"];
NSDate *date2 = [dateFormatte dateFromString:ServerDate];
unsigned int unitFlags = NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date1 toDate:date2 options:0];
int days = [comps day];
NSLog(#"%d",days);
You cannot compare two date string initially you have to convert that string to two date by using the following code
// The current date :2013-06-27 13:51
// The server date :2013-06-27 11:51
NSString *serverDate = #"2013-06-27 13:51";
NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
[datePickerFormat setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[datePickerFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *convertedDate = [datePickerFormat dateFromString:serverDate];
NSLog(#"date %#",convertedDate);
after conversion you can compare using the following code as said by #prince
NSDate *today = [NSDate date]; // current date
NSDate *newDate = self.serverDate; // other date
NSComparisonResult result;
result = [today compare:newDate]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"today is less");
else if(result == NSOrderedDescending)
NSLog(#"newDate is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same");
else
NSLog(#"Date cannot be compared");
I'm new to iOS programming and I've been looking a lot for a way to compare "today" (an NSDate) to a formatted string date (dd/MM/yyyy).
I've found some good answers with the NSDate's earlierDate, laterDate etc. but the code doesn't seem to work in my project.
here it is :
// [book quandd] is the string : 25/02/2011 (or whatever dd/MM/yyyy date)
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
if ( [[dateFormat dateFromString:[book quandd]] isEqualToDate:today]) {
NSLog(#"Dates are equal");
}
if ( [[dateFormat dateFromString:[book quandd]] earlierDate:today]) {
NSLog(#"earlier");
}
if ( [[dateFormat dateFromString:[book quandd]] laterDate:today]) {
NSLog(#"later");
}
Whatever I do and whatever the date in [book quandd], the console always writes "earlier" and "later", as if they were later and earlier at the same time than today.
Where is that "bug" coming from ?
Is there some easy/easier way to compare the today date with 26/02/2011 for example ?
An NSDate includes both date and time. No two NSDate values will be equal unless the times are identical down to the millisecond (if not finer). When you do [NSDate date] you get the exact time of "now", while if you use NSDateFormatter to convert a string to date (with no time value) then midnight is used.
If you want to see if two NSDates fall on the same day you can use NSCalendar & NSDateComponents. Or you can "cheat" and format both dates to a date string with no time value and compare the strings.
- (void) CompareDate:(NSDate*)date1 toDate:(NSDate*)date2 {
NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setDateFormat:#"yyyyMMdd"];
// Note that you should set the appropriate timezone if you don't want the default.
NSString* date1Str = [fmt stringFromDate:date1];
NSString* date2Str = [fmt stringFromDate:date2];
switch ([date1Str compare:date2Str]) {
case NSOrderedAscending:
NSLog(#"Date 1 is earlier");
break;
case NSOrderedSame:
NSLog(#"Dates are equal");
break;
case NSOrderedDescending:
NSLog(#"Date 2 is earlier");
break;
}
}
Use timeIntervalSinceNow: to get the diff from the necessary date.
You should also try to get the difference between them and then convert to a string.
use this
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
if ( [[dateFormat dateFromString:[book quandd]] compare:today]==NSOrderedSame) {
NSLog(#"Dates are equal");
}
if ( [[dateFormat dateFromString:[book quandd]] compare:today]==NSOrderedAscending) {
NSLog(#"earlier");
}
if ( [[dateFormat dateFromString:[book quandd]] laterDate:today]==NSOrderedDescending) {
NSLog(#"later");
}
You need to check return value of the earlierDate with one of the dates referred. Ex: if([date1 earlierDate:date2] == date1)
Your "bug" happens because laterDate and earlierDate return the date object that is either earlier or later. The return object is always nonnil, so both if statements evaluate to true. The correct way to use them is this way:
NSString *book = #"19/08/2014";
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSDate *date = [dateFormat dateFromString:book];
if ( [date timeIntervalSinceDate:today] == 0) {
NSLog(#"Dates are equal");
}
if ( [date laterDate:today] == today ) {
NSLog(#"earlier");
}
if ( [date laterDate:today] == date) {
NSLog(#"later");
}
Alternatively, I've used timeIntervalSinceDate, which returns the seconds between the first date and the second date.
NSString *book = #"19/08/2014";
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSDate *date = [dateFormat dateFromString:book];
if ( [date timeIntervalSinceDate:today] == 0) {
NSLog(#"Dates are equal");
}
if ( [date timeIntervalSinceDate:today] < 0 ) {
NSLog(#"earlier");
}
if ( [date timeIntervalSinceDate:today] > 0) {
NSLog(#"later");
}