Reputation: 61
i have this javascript:
var data = '<Message>Fermata 1494 - Linea R2 -> 14:01 Linea 202 -> 14:06 </Message>';
var arr = data.match(/[\w\d]+\s*->\s*[\d:]+/g);
alert(arr);
for(var i=0; i < arr.length; i++) {
arr[i] = arr[i].replace('->', 'at');
arr[i] = arr[i]+'\n';
}
arr = arr.join('');
console.log(arr);
it fetches a formatted page and prints this information:
R2 at 14:01
202 at 14:06
jsfiddle: JsFiddle
i need to print in
R2 at 14:01 - arrives in x minutes
format...
so i need to convert "14:01" part of the string in current timestamp and then do a substraction but seems tha i cant do it, in pure javascript, no jquery.
Upvotes: 1
Views: 824
Reputation: 97150
Should be close to this. Little bit tricky, because I don't know how it rolls over on midnight.
function handleMessage(message) {
var now = new Date();
var list = message.match(/[\w\d]+\s*->\s*[\d:]+/g);
var result = list.map(function(entry) {
return handleEntry(entry, now);
}).join("\n");
alert(result);
}
function handleEntry(entry, now) {
var parts = entry.split(" -> ");
var line = parts[0];
var time = parts[1];
var minutesToGo = getMinutesToGo(time, now);
return ("Line " + line + " arrives in " + minutesToGo + " minutes");
}
function getMinutesToGo(time, now) {
var parts = time.split(":");
var timeMinutes = (parseInt(parts[0]) * 60) + parseInt(parts[1]);
var nowMinutes = (now.getHours() * 60) + now.getMinutes();
var oneDayMinutes = 24 * 60;
return (oneDayMinutes + timeMinutes - nowMinutes) % oneDayMinutes;
}
var message = '<Message>Fermata 1494 - Linea R2 -> 14:01 Linea 202 -> 14:06 </Message>';
handleMessage(message);
Upvotes: 1
Reputation: 507
Assume the date is today, you can construct the date string like this:
var today =new Date();
var dateStr=today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate()
+" 14:01"+ ":00"; // attach hh:mm
Upvotes: 0