I'm trying to generate an array of 30 days from the current date and put them into an array formatted correctly. I currently have a working generater to get 30 days from the current date and put it into an array but I don't know how to use NSDate formatter for an array. I know how to use the formatter for a single item but how can I format all the dates in my array? The format that I would like is (Month Day). Here's my code:
NSMutableArray* dates = [[NSMutableArray alloc] init];
int numberOfDays=30;
NSDate *startDate=[NSDate date];
NSDate *tempDate=[startDate copy];
for (int i=0;i<numberOfDays;i++) {
NSLog(#"%#",tempDate.description);
tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
[dates addObject:tempDate.description];
}
NSLog(#"%#",dates);
Any help would be appreciated, Thanks.
i suggest you to give the NSDate formatter to your date first and then give those objects to the NSMutableArray and whenever you fetch the object from an array you get the required format.
Hope you get my point...Good Luck!
use like this,
NSMutableArray* dates = [[NSMutableArray alloc] init];
int numberOfDays=30;
NSDate *startDate=[NSDate date];
NSDate *tempDate=[startDate copy];
for (int i=0;i<numberOfDays;i++) {
NSLog(#"%#",tempDate.description);
tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd"];
NSString *dateString = [dateFormat stringFromDate:tempDate];
tempDate=[dateFormat dateFromString:dateString];
[dateFormat release];
[dates addObject:tempDate.description];
}
NSLog(#"%#",dates);
Related
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);
}
Need to compare two variables of type NSDate.
One is the current date and the other is user selected date.
The user selects the date :
UIDatePicker *datePicker; // declared in h file
-(void)dateChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MM-yyy"];
dateLabel.text = [NSString stringWithFormat:#"%#", [df stringFromDate:datePicker.date]];
userDebtInfo.duration = dateLabel.text;}
Validation Method :
-(IBAction) validation:(id)sender{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];
if ((userDebtInfo.debt_code == userTmp.debt_code) && ([userDebtInfo.duration compare:dateString]== NSOrderedDescending)))
[bl updateUserMoneyValidation:userDebtInfo];
else
[bl saveUserMoneyValidation:userDebtInfo];}
I have tested and is comparing two strings. Can someone help me with some advice about this condition, please?
I want to compare if the selected date is after the current date to do insert or update the database.
Thank you!
You could use NSDate compare function
if([firstDate compare:secondUpdate] == NSOrderedAscending){
//This will return YES if secondUpdate is the recent date between the two dates
}
NSOrderedAscending is a constant of NSComparisonResult
Here are the other constants you could compare to:
enum {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
If you already have two objects of type NSDate, you could use one of the NSDate comparison methods. For instance [NSDate compare:] which returns a NSComparisonResult (this is the same enum as returned by [NSString compare:]).
I have two times :
10:23:51
10:31:54
Both values are stored as strings in a SQLite database.
I want to find the difference between these two times in hh:mm format.
How can I do this?
I have searched a lot. But can't find a proper solution.
Help me out.
Thanks.
Edit :
See basically I am having two arrays:
InTimeArray and OuttimeArray.
Now in the viewDidload method , I am fetching all the intime entries in the IntimeArray and Outtime entries in the outtime Arrays.
Now I am passing one by one values in tableview like in 1st row
IntimeArray[0]
OuyTimeArray[0]
second row:
IntimeArray[1]
OuyTimeArray[1]
Now I want to count the differences between 1st row's intime and outtime in HH:MM format.
I am really confused.
you can take a look at that :
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [dateFormat dateFromString:string];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
this will turn the NSDate to you and when you change them both to NSDates then you can learn the difference by looking at this.
i hope this will help you..
You have to first change your both strings into date format using this method :-
- (NSDate *)dateFromString:(NSString *)string;
after that you just have to calculate number of seconds between both the dates.Thats it.
OR there is another simple way to do this. i.e.
get dates from both arrays first like this:-
NSDate *eventStartDate = [IntimeArray objectAtIndex:indexpath.row];
NSDate *eventEndDate = [OuyTimeArray objectAtIndex:indexpath.row];
Then calculate difference between both the dates like this :-
NSTimeInterval startTimeInterval = [eventStartDate timeIntervalSinceDate:currentDate];
Hope it helps Thanks :)
Try this:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *d1 = [formatter dateFromString:IntimeArray[0]];
NSDate *d2 = [formatter dateFromString:OuyTimeArray[0]];
NSTimeInterval ti = [d2 timeIntervalSinceDate:d1];
float hours = floor(ti / 3600);
float minutes = floor((ti - hours*3600) / 60);
NSString *s = [NSString stringWithFormat:#"%02.0f:%02.0f",hours,minutes];
For your given example, NSLog(#"Time passed: %#",s); will print 00:08.
I have an NSArray containing date/time NSStrings in the following format:
2/2/2011 2:46:39 PM
2/4/2011 11:59:47 AM
…
where the date is represented as month/day/year.
How do I sort this NSArray making sure the newest date/times are at the top?
When you’re dealing with dates, use NSDate instead of NSString. Also, it’s important to consider the time zone — does the Web service provide dates in UTC or some other time zone?
You should first convert your array of strings into an array of dates. Otherwise, you’d be converting a string to a date whenever it is used for comparison, and there will be more comparisons than the number of strings.
For example:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MM/DD/YYYY hh:mm:ss a"];
NSMutableArray *dateArray = [NSMutableArray array];
for (NSString *dateString in array) {
NSDate *date = [formatter dateFromString:dateString];
if (date) [dateArray addObject:date];
// If the date is nil, the string wasn't a valid date.
// You could add some error reporting in that case.
}
This converts array, an array of NSStrings, to dateArray, a mutable array of NSDates. The date formatter uses the system time zone. If you want to use UTC as the time zone:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MM/DD/YYYY hh:mm:ss a"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
Having done that, sorting the array is trivial:
[dateArray sortUsingSelector:#selector(compare:)];
Use method compare to compare two dates,
Sample NSDate comparision,
NSDate *dateOne = [NSDate dateWithString:#"2008-12-04 03:00:00 +0900"];
NSDate *dateTwo = [NSDate dateWithString:#"2008-12-04 04:00:00 +0900"];
switch ([dateOne compare:dateTwo]){
case NSOrderedAscending:
NSLog(#”NSOrderedAscending”);
break;
case NSOrderedSame:
NSLog(#”NSOrderedSame”);
break;
case NSOrderedDescending:
NSLog(#”NSOrderedDescending”);
break;
}
Use you own logic to sort
use this
NSMutableArray *mutArr=[yourArray mutableCopy];//convert your NSArray into mutable array
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorealese];
[df setDateFormat:#"MM/DD/YYYY hh:mm:ss a"];
NSDate *compareDate;
NSInteger index;
for(int i=0;i<[mutArray count];i++)
{
index=i;
compareDate=[df dateFromString:[mutArray objectAtIndex:i]];
NSDate *compareDateSecond;
for(int j=i+1;j<counter;j++)
{
compareDateSecond=[df dateFromString:[mutArr objectAtIndex:j]];
NSComparisonResult result = [compareDate compare:compareDateSecond];
if(result == NSOrderedAscending)
{
compareDate=compareDateSecond;
index=j;
}
}
if(i!=index)
[mutArr exchangeObjectAtIndex:i withObjectAtIndex:index];
}
}
NSLog(#"%#",mutArr);
I'm working on an assignment that allows the user to display events that are happening 'today'. I have parsed the XML file and stored the contents into an array. The contents of the XML file consists of a title, description, date etc. The dates are in NSString format and I want to convert them into NSDates and compare them with today's date before displaying them in a UITableView.
I'm new to obj-c and I've searched online for help on NSDate, but I couldn't find what I need. Any links, advice or help on this is really appreciated. Thanks in advance (:
suppose dateString contains the date in string format
first get date from string:-
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/mm/yyyy"];
NSDate *dateprevious = [formatter dateFromString:dateString];
Now get today date
NSDate *date=[NSDate date];
[formatter setDateFormat:#"dd"];
NSString *dateOfGame =[formatter stringFromDate:dateprevious];
NSString *todaydate =[formatter stringFromDate:date];
[formatter release];
if([todaydate isEqualToString:dateknown])
{
NSLog(#"date matched");
}
Depending on the format of the string, you can use this:
+ (id)dateWithNaturalLanguageString:(NSString *)string
To compare two dates you will find here a lot of usefull answers :)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy , hh:mm a"];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSDate *date = [[dateFormatter datefromString:date] retain];
[dateFormatter release];
You can use this one
Have a look at NSDateFormatter
It has a method called dateFromString
Like you could do the following:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/mm/yyyy"];
NSDate *date = [formatter dateFromString:#"5/5/2011"];