I have the following problem: I am building an app that is a TV Guide. I am parsing the listing for the channels from a xml file on the internet. This is my code:
-(void)loadListing
{
NSURL *urlListing = [NSURL URLWithString:#"http://pik.bg/TV/bnt1/29.03.2013.xml"];
NSData *webDataListing = [NSData dataWithContentsOfURL:urlListing];
NSString *xPathQueryListing = #"//elem/title";
TFHpple *parserListing = [TFHpple hppleWithXMLData:webDataListing];
NSArray *arrayListing = [parserListing searchWithXPathQuery:xPathQueryListing];
NSMutableArray *newArrayListing = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in arrayListing)
{
Listing *shows = [[Listing alloc] init];
[newArrayListing addObject:shows];
shows.broadcast = [[element firstChild] content];
}
_shows = newArrayListing;
[self.tableView reloadData];
}
Look at the first row - my file's name is /.../01.04.2013.xml
Tomorrow's file will be /.../02.04.2013.xml and etc.
How to make it parse different files depending on the current date? Like this: today parses /.../01.04.2013, tomorrow will parse /.../02.04.2013 and etc. ? Thanks in advance!
First of all, Get today's Date with the same format used in URL. (You have to play with separate date, month and year components)
Then, Convert that date into a NSString object
Form a NSString like NSString *strToDay = [NSString
stringWithFormat:#http://pik.bg/TV/bnt1/%#.xml",strToDay];
Use the string into the NSURL, like;
NSURL *urlListing = [NSURL URLWithString:strToDay];
NOTE This solution will work only if your URL contains the date format as specified by you.
You could use an NSDateFormatter, property configured, to generate a string of the appropriate format. Use the NSDate instance returned by [NSDate date] to get today's date, and use the formatter to generate the string. Finally, insert the string representation of the date into the URL string and build an NSURL from it.
// Assuming the TV schedule is derived from the Gregorian calendar
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Use the user's time zone
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
// Instantiate a date formatter, and set the calendar and time zone appropriately
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:gregorianCalendar];
[dateFormatter setTimeZone:localTimeZone];
// set the date format. Handy reference here: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
[dateFormatter setDateFormat:#"dd.MM.yyyy"];
// [NSDate date] returns a date corresponding to 'right now'.
// Since we want to load the schedule for today, use this date.
// stringFromDate: converts the date into the format we have specified
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
// insert the date string into the URL string and build the URL
NSString *URLString = [NSString stringWithFormat:#"http://pik.bg/TV/bnt1/%#.xml", dateString];
NSURL *URL = [NSURL URLWithString:URLString];
NSLog(#"URL = %#", URL);
i have one array something like below
Birthdates(
"03/12/2013",
"03/12/2013",
"08/13/1990",
"12/09/1989",
"02/06",
"09/08",
"03/02/1990",
"08/22/1989",
"03/02",
"05/13",
"10/16",
"07/08",
"08/31/1990",
"04/14/1992",
"12/15/1905",
"08/14/1989",
"10/07/1987",
"07/25",
"07/17/1989",
"03/24/1987",
"07/28/1988",
"01/21/1990",
"10/13"
)
all are NSString
now i want to make another array from this in which all years should be 2013 if that date is coming in current year and if date is already passed then change year to 2014?
in above sentence we are not considering year we consider only day and month and then see in current year is it already passed or not?
example if date is "12/15/1905" then convert it in another array like "12/15/2013"
but if date is like "01/01/1990" then convert it in another array like "01/01/2014"
bcoz it has already passed current date
plz help thank you in advance :)
i will prefer to do something in which code apply for not only 2013 and 2014 it should apply for coming future too.
This code will do for you :
NSArray *Birthdates=#[
#"03/12/2013",
#"03/12/2013",
#"08/13/1990",
#"12/09/1989",
#"02/02",
#"09/08",
#"03/02/1990",
#"08/22/1989",
#"03/02"];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger currentYear = [components year];
NSMutableArray *newBirthDates=[NSMutableArray new];
for(NSString *str in Birthdates){
NSArray *array=[str componentsSeparatedByString:#"/"];
if(array.count==2){
NSString *tempString=[NSString stringWithFormat:#"%#/%d",str,currentYear];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSDate *date=[dateFormatter dateFromString:tempString];
if ([[NSDate date] isGreaterThanOrEqualTo:date]) {
NSLog(#"passed->%# *** %#",date, str);
[newBirthDates addObject:[NSString stringWithFormat:#"%#/%d",str,currentYear+1]];
}
[newBirthDates addObject:tempString];
}
else{
NSString *dateString=[NSString stringWithFormat:#"%#/%#/%d",array[0],array[1],currentYear];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSDate *date=[dateFormatter dateFromString:dateString];
if ([[NSDate date] isGreaterThanOrEqualTo:date]) {
dateString=[NSString stringWithFormat:#"%#/%#/%d",array[0],array[1],currentYear+1];
}
[newBirthDates addObject:dateString];
}
}
NSLog(#"%#",newBirthDates);
Here is the Output:
DocumentBased[6632:303] (
"03/12/2014",
"03/12/2014",
"08/13/2013",
"12/09/2013",
"02/02/2014",
"09/08/2013",
"03/02/2014",
"08/22/2013",
"03/02/2014"
)
This code is same as Anoop Vaidya code upto fetching all the dateStrings into one format. but the date comparision logic which fails in Anoop code is over comed here i.e., when count == 2..
Here is my edited code respect to Anoop
NSArray *Birthdates=#[
#"03/12/2013",
#"03/12/2013",
#"08/13/1990",
#"12/09/1989",
#"02/06",
#"09/08",
#"03/02/1990",
#"08/22/1989",
#"03/02"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy"];
NSString *curYear = [dateFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSMutableArray *newBirthDates=[NSMutableArray new];
for(NSString *str in Birthdates){
NSArray *array=[str componentsSeparatedByString:#"/"];
if(array.count==2){
[newBirthDates addObject:[NSString stringWithFormat:#"%#/%#",str,curYear]];
}
else{
[newBirthDates addObject:[NSString stringWithFormat:#"%#/%#/%#",array[0],array[1],curYear]];
}
}
for(int i = 0; i < [newBirthDates count]; i++)
{
NSString *dateStr = [newBirthDates objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare:[NSDate date]];
if(comResult == NSOrderedAscending)
{
[dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
[newBirthDates replaceObjectAtIndex:i withObject:dateStr];
}
}
NSLog(#"%#",newBirthDates);
This will work in all the scenarios...
I take it you know how to use the NSDateFormatter to format dates, to change the year alone, just check this link NSDateComponents. Please have a look at this StackOverflow question on how to split the date into NSDateComponents.
I think You can check it directly without using dateFormatter.
Steps to do:
First find the current date with NSDate.Convert it into string and make the format as same the array you have, by using NSDateFormatter.
Next compare one by one by making condition .
Separate the string by "/" .
if([myArray objectAtIndex:i]string separate by#"/" objectAtIndex:0 )
and the check the next one ...
Make the condition as you want
I hope if you do like this with less lines of code you can achieve what you want.
I am getting a date string back from a web service which looks like this:
/Date(12924576000000+0000)/
Can anyone tell me how to format this into a readable string?
Thanks.
Here is how I'm doing it:
NSString * json_parsed_date = #"/Date(12924576000000+0000)/";
NSString* tsString = [json_parsed_date substringWithRange:NSMakeRange(6,10)];
NSNumber* timestamp = [NSNumber numberWithInteger:[tsString intValue]];
NSDate * dateObject = [NSDate dateWithTimeIntervalSince1970:[timestamp intValue]];
For human readable string:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSString *theDate = [dateFormat stringFromDate:dateObject];
I am making an iphone application in which I want to implement the alarm concept. I am using time picker for time but I am getting the time 2011-08-17 17:00:45 +0530 in this format. Now I want to get the hours, min and seconds different by using range concept or any other concept. How can I do it. Please help me.
Thanks in advance.
Try this
NSDateFormatter *format = [[[NSDateFormatter alloc]init] autorelease];
[format setDateFormat:#"HH:mm:ss"];
NSString strTime = [NSString stringWithFormat:#"%#",[format stringFromDate:yourDate]];
And then separate the string into components :
NSArray *arr = [str componentSeparatedBy:#" "];
NSString *strHours = [arr objectAtIndex:0];
NSString *strMinutes = [arr objectAtIndex:1];
NSString *strSeconds = [arr objectAtIndex:2];
Now convert hours and minutes into seconds :
int iHours = [strHours intValue];
if(iHours>12) //Check for hour more than 12:00 eg 17:00
{
iHours = iHours - 12;
}
int iMinutes = [strMinutes intValue];
int iSeconds = [strSeconds intValue];
intTotalSeconds = (60*60*iHours) + (60*iMinutes) + iSeconds;
iTotalSeconds are the total seconds you require.
If you want to convert the String to NSDate use:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init]
[format setDateFormat:#"yyyy-MM-dd HH:mm:ss ZZZZ"];
NSDate* foo = [dateFormatter dateFromString:yourDateString];
After that you can convert the NSDate to NSDateComponents and get the seconds, minutes etc. from them.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:
(NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:foo];
NSInteger second = [component second];
NSInteger minute = [component minute];
Either do a mashup of #Nitish and #cortez's answers (use one DateFormatter to parse the date string, and another to output it in your preferred format), or:
Download and include RegexKitLite in your project.
Then go:
#import "RegexKitLite.h"
NSString *timeString = #"2011-08-17 17:00:45 +0530";
NSString *regex = #"\d{2}:\d{2}:\d{2}";
NSString *timeComponent = [timeString stringByMatching:regex capture:1];
HELLO i am trying to insert Current date in my database table
i have a column dateVisited of type datetime
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy/MM/dd HH:mm:ss"]; //this is the sqlite's format
NSDate *stringTime = [NSDate date];
NSString *formattedDateStringTime = [formatter stringFromDate:stringTime];
sqlStr = [NSString stringWithFormat:#"Insert into AnwaltHistory (id,dateVisited) values (%d,'%#')",Id formattedDateStringTime];
NSLog(#"%#",sqlStr);
BOOL Res = [appDelegate InsUpdateDelData: sqlStr];
if (Res)
{
NSLog(#"The Following instrunction is excuted successfully !");
}
else
{
NSLog(#"The Following instrunction Failed to execute !");
}
the statement executes successfully but when i actually go and check the table it says invalid date... i dont know why
as i have printed sqlstr i copy paste from the console and paste it in sqlite and run it manually it runs perfectly fine and has the actual date....
can any one guide me where i am mistaken :S.......
please
Why not use:
"Insert into AnwaltHistory (id,dateVisited) values (%d,datetime())",Id
You could try this:
double dateVisited = [[NSDate date] timeIntervalSince1970]; //now
// save dateVisited to your 'dateVisited' field
According to the official documents, the DateTime on SQLITE should be in ISO8601 format (AKA: a string of ("YYYY-MM-DD HH:MM:SS.SSS"))
Therefore, to store the date, you should format your date string, below is a code to help you with this:
NSDate *SourceDate = [NSDate date]; // Or whatever NSDATE you like...
NSDateFormatter *MyDateFormatter = [[NSDateFormatter alloc] init];
[MyDateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss.SSS"];
NSString *SQLiteQuery = [NSString stringWithFormat:#"Insert into YourTable(YourDateField) values ('%#')", [MyDateFormatter stringFromDate:SourceDate]];
This should do it, give's a shout if you need more help,
Cheers
H