Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  95] [ 7]  / answers: 1 / hits: 27970  / 13 Years ago, tue, february 14, 2012, 12:00:00

I have a text file located on the server that contains a list of events with their target time. It looks something like the following:



2012/02/11-10:00:00 EventStart Red
2012/02/11-10:10:00 EventStop Green
...


What I need to do is somehow read the text file and based on the current time select the next upcoming event and assign each element for that event to a variable. So for example if the time is currently 2012.02.11-10:08:00, javascript variables time = '2012/02/11-10:10:00'; title = 'EventStop'; color = 'Green'; would be created.



I'm able to read the text file with:



jQuery.get('schedule.txt',function(data){
alert(data);
});


Just don't know where to go from there, or if that's even the best way to start. I do have control over the formatting of the text file, so modifying that is an option.


More From » jquery

 Answers
24

You say you can modify the file's contents, so I suggest converting it to JSON (and separating the date/time).



[{date: 2012/02/11, time: 10:00:00, title: EventStart, color: Red}, {date: 2012/02/11, time: 10:10:00, title: EventStop, color: Green}]


Then you can use getJSON to get/parse it.



jQuery.getJSON('schedule.txt',function(data){
// data is an array of objects
$.each(data, function(){
console.log(this.title); // log each title
});
});


From here, you can read the times and figure out which one is the latest. Something like this should work:



if(Date.now() <= Date.parse(this.date+' '+this.time))


So, putting it all together:



jQuery.getJSON('schedule.txt',function(data){
var matchedSchedule = {};
// data is an array of objects
$.each(data, function(){
if(Date.now() <= Date.parse(this.date+' '+this.time)){
matchedSchedule = this; // If time matches, set a variable to this object
return false; // break the loop
}
});
console.log(matchedSchedule.title);
// to set a global variable, add it to `window`
window.eventTitle = matchedSchedule.title;
});

[#87461] Tuesday, February 14, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;