I need to compare two dates with time (am/pm). I used the following code.
-(NSDate*)dateFromString:(NSString*)dateString{
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd H:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateString];
[dateFormat release];
return date;
}
#define kMinute 60
#define kHour (60*60)
#define kDay (60*60*24)
-(NSString*)textFromSeconds:(double)seconds{
if(seconds < kMinute)
return [NSString stringWithFormat:#"%0.0f seconds",seconds];
if(seconds < kHour)
return [NSString stringWithFormat:#"%0.0f minutes",seconds/kMinute];
if(seconds < kDay)
return [NSString stringWithFormat:#"%0.0f hours",seconds/kHour];
return [NSString stringWithFormat:#"%0.0f days", seconds/kDay];
}
-(NSString*)textFromDateString:(NSString*)dateString{
NSDate *date =[self dateFromString:dateString];
double seconds = [[NSDate date] timeIntervalSinceDate:date];
NSString *text = [self textFromSeconds:seconds];
NSLog(#"text is: %#", text);
return text;
}
-(void)test{
[self textFromDateString:#"2011-02-20 17:19:25"];
[self textFromDateString:#"2011-02-20 17:10:25"];
[self textFromDateString:#"2011-02-20 14:04:25"];
[self textFromDateString:#"2011-02-19 14:04:25"];
}
Its working perfect. But I need to convert this into 12 hour clock. So that I need to compare two dates with AM or PM. What modifications should I do in the above code to achieve the goal?
I changed the dateformat to #"yyyy-MM-dd HH:mm a" and tried with date in the same format, But its not working.
Thanks.
Try changing the dateformat to #"yyyy-MM-dd hh:mm a"
Related
I have start date and end date in string format.i want to compare end date and start date,end date should be greater than start date.How to do this.
NSLog(#"%#",date);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd MM yyyy"];
_start_date = [[NSDate alloc] init];
_start_date = [df dateFromString: date];
NSLog(#"date: %#", _start_date);`
Getting nil on start_date.
You need to convert both the strings to NSDate objects using NSDateFormatter.
As your date is in dd-MM-yy format, do as shown below :
NSString *dateStr1 = #"21-3-14";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"dd-MM-yy"];
NSDate *date1 = [dateFormatter dateFromString:dateStr1];
Similarly create another date, say date2 Then you can compare these dates.
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
Create an instance of NSDateFormatter.
Configure it.
Parse the strings to get NSDate objects (dateFromString:).
Compare them (compare:).
I have two NSString which have date i want that if they both have same data then if should work otherwise else should work
here is my code
NSString*test=data.addedDateTime;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSDate* date = [NSDate date];
NSString* str = [formatter stringFromDate:date];
NSString*addedDateTime=str;
if ([test isEqualToString:str]) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else {
[yesterdayArray addObject:theObject];
}
my code always runs else when there is same value in both i have checked using NSLog
Don't compare two NSStrings, which represent the dates, but compare two NSDates instead
First you convert string to date and use this [date1 isEqualToDate:date2].This is a compair a two date.
use this code I hope this code useful for you.
NSString*test=data.addedDateTime;
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy_MM_dd"];
NSDate* d = [df dateFromString:test];
[df release];
NSDate* date = [NSDate date];
if ([d isEqualToDate:date) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else {
[yesterdayArray addObject:theObject];
}
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);
Condition [test isEqualToString:str] always gives NO if date is either not equal or in not same formate. So dont use this.
Use NSDateComponent to compare two dates or Compare as #Andrey Gordeev
Says .
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 string "test" into date format using dateFromString function of the formatter by specifying the exact date format as that of the test. Then compare the dates using following function.
NSString*test=data.addedDateTime;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSDate *newDate = [formatter dateFromString:data.addedDateTime]; // other date
NSDate *today = [NSDate date]; // current date
NSComparisonResult result;
result = [today compare:newDate]; // comparing two dates
if(result == NSOrderedSame)
{
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else
{
[yesterdayArray addObject:theObject];
}
Instead of comparing String compare Date. Like this,
NSDate *myDate1 =data.addedDateTime;
NSDate* mydate2 = [NSDate date];
if ([myDate1 compare:mydate2] == NSOrderedDescending) {
NSLog(#"Dilip myDate1 is later than myDate2");
} else if ([myDate1 compare:mydate2] == NSOrderedAscending) {
NSLog(#"Dilip myDate1 is earlier than myDate2");
} else {
NSLog(#"Dilip dates are the same");
}
first u should convert date to nsstring..
then u set perfect date formate in both string..
like
NSDate *today1 = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSString *dateString11 = [dateFormat stringFromDate:today1];
[dateString11 retain];
ur first string is like dateString11
and other date string is like str2=#"03-10-2010";
then u compare two string
if ([dateString11 isEqualToString:str2]) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
I get JSON Parse Date, I want to use NSDateFormatter,but not success.
1.JSON Get console Log
IncidentReceiveTime = "/Date(1353914100000+0800)/";
2.my code
NSString *dateStr =[NSString stringWithFormat:#"%#",[[[DateSortArry objectAtIndex:0] objectForKey:#"IncidentReceiveTime"]stringByReplacingOccurrencesOfString:#"/" withString:#""]];
NSLog(#"dateStr:%#",dateStr);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:#"yyyy-MM-ddHH"];
NSDate *date = [dateFormatter dateFromString:dateStr];
NSLog(#"date:%#",date);
3.NSDateFormatter console log
dateStr:Date(1361943694000+0800)
date:(null)
Refer to my answer in :
iPhone:How to convert Regular Expression into Date Format?
Here I am posting this code from my answer in the above link as if in case in future the above link goes down then this answer doesn't become useles:
- (NSDate*) getDateFromJSON:(NSString *)dateString
{
// Expect date in this format "/Date(1268123281843)/"
int startPos = [dateString rangeOfString:#"("].location+1;
int endPos = [dateString rangeOfString:#")"].location;
NSRange range = NSMakeRange(startPos,endPos-startPos);
unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
NSLog(#"%llu",milliseconds);
NSTimeInterval interval = milliseconds/1000;
return [NSDate dateWithTimeIntervalSince1970:interval];
}
Once you get NSDate object from above method:
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
[dateForm setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSString *dateStr = [dateForm stringFromDate:<YourNSDateObject>];
[dateForm setDateFormat:#"<Your Desired Date Format>"];
NSDate *desireddate = [dateForm dateFromString:dateStr];
Hope this helps.
I am doing an application where I am using the following link http://iosdevelopertips.com/cocoa/date-formatters-examples-take-3.html to convert the date from string.
I am using below code to same by following above tutorial link. when I NSlog PresentDateTime it gives 20120111 13:03:49.263+05:30.
so I am taking this format and want to convert into the format of "EEEE MMMM d, YYYY h:mm a, zzz".
To do so when I assign the same to the variable
NSString *today = presentDateTime;
when I NSLog Datestring I am getting result NULL can I know where I am going wrong? please help me to solve this issue by suggesting what changes to be done
//code
-(NSString *)DateFormat:(NSString *) presentDateTime
{
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:#"T" withString:#" "];
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:#" +" withString:#"+"];
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSLog(#"Present date::::%#",presentDateTime);
NSString *today = presentDateTime;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd HH:mm:ss:SSSZZZ"];
NSDate *date = [dateFormat dateFromString:today];
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY h:mm a, zzz"];
NSString *dateString = [dateFormat stringFromDate:date];
[dateFormat release];
NSLog(#"dateString:::Date>>>>:%#::::\n%#",dateString, presentDateTime);
return dateString;
Your date format pattern for parsing the date is wrong/incomplete. For the string 20120111 13:03:49.263+05:30 the format would be YYYYMMdd HH:mm:ss.SSSZZZ. See this table for the format string patterns.
Edit: After playing around with the code, it turns out that the NSDateParser chokes on the timezone +05:30. It expects +0530, without the colon. Here's how to remove it:
NSString *today = #"20120111 13:03:49.263+05:30";
NSRange colon = [today rangeOfString:#":" options:NSBackwardsSearch];
if (colon.location != NSNotFound) {
today = [today stringByReplacingCharactersInRange:colon withString:#""];
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYYMMdd HH:mm:ss.SSSZZZ"];
NSDate *date = [dateFormat dateFromString:today];
NSLog(#"%#", date);
When you parse your original date string you need to specify the entire format, like this:
[dateFormat setDateFormat:#"yyyyMMdd HH:mm:ss.SSSZZZ"]
Compare your code with the following
NSString *dateString = #"6:30 18 Oct";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm dd/MMM"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
Its just sample to follow. and figure out what is going wrong by printing it in nslog.
Your date variable is always nil because your date format (yyyyMMdd) is incomplete as your input string today contains extra information (20120111 13:03:49.263+05:30). So you can just crop unnecessary characters:
if ([presentDateTime count] < 8) return nil;
NSString *today = [presentDateTime substringToIndex:8];
Or you should specify full date format as mentioned by #jonkroll
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);