This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If “a == b” is false when comparing two NSString objects?
In an "if" statement I'm comparing two strings, "currentDateString" and "dateCreatedString", to get "Today" if true and "dateCreatedString" if false. Although they should be equal when creating a new item, the if statement is returning false every time and just giving the currentDateString when I'm looking to get "today".
- (NSString *)dateCreatedString
{
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *dateCreatedString = [dateFormatter stringFromDate:[_detailItem dateCreated]];
return dateCreatedString;
}
- (NSString *)currentDateString
{
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *currentDateString = [dateFormatter stringFromDate:[NSDate date]];
return currentDateString;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//places "Today" in the dateLabel if the two strings both equal today
if ([self currentDateString] == [self dateCreatedString] || [_detailItem dateCreated] == nil) {
[_dateTxt setText:#"Today"];
}
else{
[_dateTxt setText:[self dateCreatedString]];
}
}
Could somebody help explain why this is happening, and how to fix it?
Thanks!
You should use isEqualToString to compare strings like this:
if ([[self currentDateString] isEqualToString:[self dateCreatedString]])
Using == you are comparing the pointers to the string objects, which certainly are not the same.
Related
I have a NSString and I need to check that it is in a this specific format MM/DD/YY. I then need to convert that to a NSDate. Any help on this would be much appreciated. Sidenote - I have searched around and people suggest using RegEx, I have never used this and am unclear about it generally. Can anyone point me to a good resource/explanation.
NSString *strDate1 = #"02/09/13";
NSString *strDate2 = #"0123/234/234";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDate *dateFormat1 = [dateFormatter dateFromString:strDate1];
NSDate *dateFormat2 = [dateFormatter dateFromString:strDate2];
NSLog(#"%#", dateFormat1); // prints 2013-09-02 00:00:00 +0000
NSLog(#"%#", dateFormat2); // prints (null)
So you will know when it's not formatted correctly if the NSDate is nil. Here's the link to the docs if you need more info: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
Use an NSDateFormatter for both tasks. If you can convert the string to a date then it is in the correct format (and you already have the result).
I know that this is a late answer, but it is impossible to always guarantee that a string is in this particular date format.
A date formatter, a regex, or even a human can not verify certain dates, because we don't know if the user is entering "mm/DD/yy" or "DD/mm/yy". It is common in some places to enter the day of the month first, while in other areas you enter the month first. So if they enter "09/06/2013" do they mean "September 6th" or the "9th of June"?
Here is a simple function for anyone searching for a simple solution.
- (BOOL) isTheStringDate: (NSString*) theString
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:theString];
if (dateFromString !=nil) {
return true;
}
else {
return false;
}
}
You have to change the formatter below to match the formatting your date is using.
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
How to get the NSDateFormatter like the one used to generate string on the right.
simply use the setDoesRelativeDateFormatting is not enough.
And using NSCal to figure out the date's relativity to now is quiet slow.
Especially when used in UITableViewCell
You can use a "fuzzy date" library such as NSDate-TimeAgo.
They are likely using 2 formatters...
maybe something like :
- (id)stringForDate:(NSDate*)date {
if(date isToday]) return time
else return date day
}
NSDateFormatter *f = [[NSDateFormatter alloc] init];
f.dateFormat = #"yyyy MM dd";
NSDate *today = [NSDate date];
NSDate *your_Date;
NSString *a = [f stringFromDate today];
NSString *b = [f stringFromDate your_Date];
if (a isEqualToString:b){
NSdateFormatter *forToday =... //with hours
} else {
NSDateFormatter *forDays = ...//days
}
This question already has answers here:
How to compare two NSDates: Which is more recent?
(13 answers)
Closed 9 years ago.
I am trying to compare two dates whether which one is the new or old, my dates are in following format:
2013-06-03 09:30:35
(YYYY-MM-DD HH:MM:SS)
Please give me some ideas, both are currently in string format?
So is that possible to convert ad check?
Convert that strings into NSDate using dateFormatter.
You can check this link Here is good discussion of your problem
How to compare two NSDates: Which is more recent?
try this
NSString to NSDate
NSString *dateString = #"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
NSDate convert to NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"%#", strDate);
[dateFormatter release];
Please read this
enter link description here
if ([yourFirstDate compare:secondDate] == NSOrderedDescending) {
NSLog(#"yourFirstDate is later than secondDate");
} else if ([yourFirstDate compare:secondDate] == NSOrderedAscending) {
NSLog(#"yourFirstDate is earlier than secondDate");
} else {
NSLog(#"dates are the same");
}
same as #DIVYU 's Link
I want to retrieve all the entries from core data added between two dates.I am using NSPredicate. As I am not getting the correct result I tried logging the date.It is showing the previous dates.After googling for a while I added
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; to my code.Now,Its showing correct dates but the results are still wrong.
This is the code I used.
NSDate *fromDate = [[self dateFormatter]dateFromString:self.fromDateField.text];
NSLog(#"%#",fromDate);
NSDate *toDate = [[self dateFormatter]dateFromString:self.toDateField.text];
NSLog(#"%#",toDate);
NSComparisonResult result = [fromDate compare:toDate];
switch (result) {
case NSOrderedAscending:
{
//code
}
- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
return dateFormatter;
}
Thanks in advance
If you log an NSDate object directly it will always display the tome in GMT/UTC timezone. you have to log the output of a date formatter.
NSLog(#"%#",[self.dateFormatter stringFromDate:toDate]);
This will take your timezone in account. Or better: the timezone of the dateformatter's calendar — what is the device default if you dont change that.
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");
}