Display Date Specific URL - javascript

Objective is to show a link on the page based on a date
Since I am very new to JS, would there be a more efficient way to achieve this?
The below code works but ideally I would like to edit the HTML and not JS every time I want a change i.e enter dates and URL in HTML file and not the JS.
Links and dates are currently added manually in the JS
<!DOCTYPE html>
<html>
<body>
<p id="ademo"></p>
<script>
var yr = new Date().getFullYear();
var mn = new Date().getMonth()+1;
var dt = new Date().getDate();
var showlink;
var showlink1 = ('URL-1');
var showlink2 = ('URL-2');
var showlink3 = ('URL-3');
var showlink4 = ('URL-4');
if (yr == 2021 && mn == 3 && dt == 15) {
showlink = showlink1;
} else if (yr == 2021 && mn == 3 && dt == 16) {
showlink = showlink2;
} else if (yr == 2021 && mn == 3 && dt == 17) {
showlink = showlink3;
} else if (yr == 2021 && mn == 3 && dt == 18) {
showlink = showlink4;
}
document.getElementById("ademo").innerHTML = showlink.toString();
</script>
</body>
</html>

You could do it by adding a data object and manage that. This could also be an external JSON file you include in your code.
Adding your data into HTML will just bloat your HTML and likely have accessibility issues you need to deal with.
const data = {
'2021-3-15': 'URL-1',
'2021-3-16': 'URL-2',
'2021-3-17': 'URL-3',
'2021-3-18': 'URL-4',
};
const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();
const key = `${year}-${month}-${day}`;
document.getElementById("ademo").innerHTML = data[key];
<p id="ademo"></p>
And if you want to us an external JSON file you'd do it this way:
async function loadData() {
const rawJson = await fetch('/url/to/your/data.json');
const data = await rawJson.json();
const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();
const key = `${year}-${month}-${day}`;
document.getElementById("ademo").innerHTML = data[key];
}
loadData();
While your JSON would be in this shape:
{
"2021-3-15": "URL-1",
"2021-3-16": "URL-2",
"2021-3-17": "URL-3",
"2021-3-18": "URL-4"
}

Related

Crawling and saving links in specific directory. Cheerio

I have a website with multiple pages (http://www.europarl.europa.eu/sides/getDoc.do?type=PV&reference=20190131&secondRef=TOC&language=EN)
I crawled each page and got links with minutes in it. Each link with minutes has a date, after I created folders with Years and Months, I stuck with a store files from links.
The question is:
How can I download links in a month directory?
function crawlLink(link){
link = 'http://www.europarl.europa.eu'+link;
request(link, (error,response,
html) => {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(html);
const docTitle = $('.doc_title' ) ;
var str = docTitle.html();
var date_str = str.replace(' - Brussels','').replace(' - Strasbourg', '');
var date = new Date(date_str);
console.log("created new dateobj", date);
var year = new Array('January','February', 'March' , 'April' , 'May' , 'June', 'July' ,'August','September','Oktober','November','December');
var mm = date.getMonth(); //January is 0
var yyyy = date.getFullYear();
var monthName = year[mm];
var yearDir = './data/'+yyyy;
if (!fs.existsSync(yearDir)){
fs.mkdirSync(yearDir);
}else{
console.log('yearDir exists');
}
var monthDir = yearDir+'/'+monthName;
if (!fs.existsSync(monthDir)){
fs.mkdirSync(monthDir);
}else{
console.log('monthDir exists');
}
console.log("wouhu everything is fine, get links and download them to monthDir");
let downloadLinks = [];
let $links = $('.doc_formats_box a');
$links.each(function(i, elem) {
downloadLinks.push({
title:$(this).text(),
link:$(this).attr('href')
});
});
console.log(downloadLinks);
`

perform redirection if event time plus 4 hours is more than current time in js

There is a variable which contains event time. I want to redirect user if event time + 04:38 is more than current time.
Below is the code i have tried:
var deadline = getDayInstance("Monday","08:00:59")
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
console.log("Event Time: "+dt);
var maxLimit = Date.parse(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
window.setVideo = false;
}
console.log(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
console.log(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
return dt;
}
var maxLimit = Date.parse(moment(deadline,'YYYY-MM-DDTHH:mm:ss').add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}
I need to maintain timezone in calculation.
I got the answer of this after refining the process theoretically and then try to implement it in JS. Below is the new code that can be used for this.
var deadline = getDayInstance("Tuesday", "02:32:00");
var maxLimit,now;
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,
"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed)
.format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
var d = new Date(dt);
d.setHours(d.getHours() + 4);
d.setMinutes(d.getMinutes() + 43);
d.setSeconds(d.getSeconds() + 32);
max = Date.parse(d);
now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
return dt;
}
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}

Kendo UI Grid - Filter - Date Range

Filtering a column by date range works nice with solution that i've found in SO
How to define a Kendo grid Column filter between two dates? - proposed by MWinstead
But
"The only problem with this solution is that if you only select the End Date and apply the filter, the next time you open the filter menu, the Begin Date will get populated with the End Date you entered and the LTE operator will be selected, which will be changed by the jQuery code, resulting in a wrong filter"
Question asked by ataravati in the same thread
How we can resolve this issue ?
The soltion is to provide the Begin Date with null value, even if the user hasn't selected it.
But, we must take control of submit button...
function grid_filterMenuInit(e) {
var currentFieldName = e.field;
if(currentFieldName === "yourFieldDate") {
console.info("ignoring this field: <" + currentFieldName + ">");
return;
}
console.info("performing this field: <" + currentFieldName + ">");
var filterSubmit = e.container.find("[type=submit]:eq(0)");
$(filterSubmit).click(function() {
var searchDateAfter = e.container.find("input:eq(0)");
var searchDateAfter1 = $(searchDateAfter).val();
var searchDateBefore = e.container.find("input:eq(1)");
var searchDateBefore1 = $(searchDateBefore).val();
var gridDatasource = $("#yourGridId").data("kendoGrid").dataSource;
var jsDateBefore = null;
var jsDateAfter = null;
// we must convert kendoDateTime to JavaScript DateTime object
// in my case the date time format is : yyyy/MM/dd HH:mm:ss
if (typeof searchDateBefore1 !== 'undefined') {
jsDateBefore = newJsDate(searchDateBefore1);
}
if (typeof searchDateAfter1 !== 'undefined') {
jsDateAfter = newJsDate(searchDateAfter1);
}
var previousFilter = gridDatasource.filter();
var previousFilters = new Array();
var newFilters = new Array();
// storing the previous filters ...
if (typeof previousFilter === 'object' && previousFilter.hasOwnProperty("filters")) {
previousFilters = previousFilter.filters;
for (var i=0 ; i<previousFilters.length ; i++) {
if (previousFilters[i].field !== currentFieldName) {
if (newFilters.length == 0) {
newFilters = [previousFilters[i]];
}
else {
newFilters.push(previousFilters[i]);
}
}
}
}
// this is the soltion : we must provide the first filter, even if the user has not provide the begin date
// and the value will be : null
if (newFilters.length == 0) {
newFilters = [{field: currentFieldName, operator: "gte", value: jsDateAfter }];
}
else {
newFilters.push ({field: currentFieldName, operator: "gte", value: jsDateAfter });
}
if (jsDateBefore !== null) {
newFilters.push ({field: currentFieldName, operator: "lte", value: jsDateBefore });
}
gridDatasource.filter (newFilters);
$(".k-animation-container").hide();
// to stop the propagation of filter submit button
return false;
});
}
function newJsDate(dateTime) {
if (dateTime === null ||
typeof dateTime === 'undefined' ||
dateTime === "") {
return null;
}
var dateTime1 = dateTime.split(" ");
var date = dateTime1[0];
var time = dateTime1[1];
var date1 = date.split("/");
var time1 = time.split(":");
var year = parseInt(date1[0], 10);
var month = parseInt(date1[1], 10);
month = month - 1;
var day = parseInt(date1[2], 10);
var hour = parseInt(time1[0], 10);
var minute = parseInt(time1[1], 10);
var second = parseInt(time1[2], 10);
var jsDate = new Date(year, month, day,
hour, minute, second);
return jsDate;
}

how to test if a value is greater than another value in an array. javascript

i'm trying to do a function in javascript inorder to catch a file that have the last date. My problème is how to compare the date value that is found in an array. I have tried the code below
//indentifiant[0] is an id that i caught in the file name
//all_response is the content of the file
var timeSusDat = stats.mtime + all_response;
if (filesPerUser[identifiant[0]]) {
filesPerUser[identifiant[0]].push(timeSusDat);
} else {
var testtab = [timeSusDat];
filesPerUser[identifiant[0]] = testtab;
};
function onlyLastDate(table) {
for (var d in table) {
id = table[d];
for (var db in table[d]) {
data = table[d][db];
date = data.split('/');
var testDate = new Date(date[0]).getTime();
console.log(testDate);
}
}
}
function rangeDate(testDate){
var dateStart = new Date($('#dateStart').val()).getTime();
var dateEnd = new Date($('#dateEnd').val()).getTime();
if (dateStart <= testDate && testDate <= dateEnd) {
date = true;
return date;
}else{
date = false;
return date;
}
}

To get the date format by customizing it

I am using a js function where i can parse only 2 different date formats.If a user wants some other Date format its not taking.
function getFormattedDate(id) {
var start = document.getElementById(id).value;
var jsDate = new Date(start);
var shortWeekday = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var fullWeekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var date1="";
<% String dateFormat1 = (String) session.getAttribute("calendarDateFormat");%>
var df = '<%= dateFormat1%>';
if(df.indexOf("EEEE") != -1) {
date1 = fullWeekday[jsDate.getDay()]+' '+jsDate.getMonth()+' '+jsDate.getDate()+' '+jsDate.getFullYear();
} else {
date1 = shortWeekday[jsDate.getDay()]+' '+jsDate.getMonth()+' '+jsDate.getDate()+' '+jsDate.getFullYear();
}
document.getElementById(id).value = date1;
}

Categories