Plugin: eonasdan/Bootstrap 3 Datepicker
Explaination:
I want to write an application that user can select 5 different hours for each day. so i created an array and add each day (without duplicate), for example user select 31/12/2017 and 30/12/2017 , now i want to give they this ability to select only 5 different hour for each day that selected.
Tried Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
dateArray[unqdate] = unqtime
}
}
console.log(dateArray);
});
JSFiddle
(For testing, select a date, then click on save button, then check console)
Goal:
var dateArray = {
"31-12-2017": [{
"time": "14:00"
}, {
"time": "17:15"
}],
"30-12-2017": [{
"time": "13:00"
}, {
"time": "12:15"
}]
}
Problem:
I couldn't figured out how can i add another time to each day. it's my first time i work with array and object like this.
I want to prevent duplicate entry and only five different hour per day.
Somehow I'm in learning.
There is some problem with your JS Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
if(dateArray[unqdate] && dateArray[unqdate].length < limit) {
if(!dateArray[unqdate].find((ele) =>ele.time === unqtime)){
dateArray[unqdate].push({"time": unqtime})
}
} else {
dateArray[unqdate] = [{"time": unqtime}]
}
}
}
console.log(dateArray);
});
Note included logic for time split. You can use split by : and take the first 2 element of array.
I have created JSON response for your requirement.
Result :: JSON.stringify(parentObject)
Code is as below.
$(document).ready(function() {
$('#datetimepicker1').datetimepicker({
stepping: 30,
sideBySide: true,
showTodayButton: true,
format: 'DD-MM-YYYY HH:mm:ss',
});
// my code
var limit = 5;
var i = 0;
var parentObject = new Object();
var parentArray = [];
var dateAndTimeObject;
function isDateSelectedExists(date) {
for (var i = 0; i < parentArray.length; i++) {
var obj = parentArray[i];
if (obj["date"] === date) {
return i;
}
}
return -1;
}
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
var tempIndex = isDateSelectedExists(unqdate);
console.log("tempIndex :: " + tempIndex);
if (tempIndex == -1) {
console.log("date doesn't exists");
dateAndTimeObject = new Object();
dateAndTimeObject["date"] = unqdate;
var timeArray = [];
timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
parentArray.push(dateAndTimeObject);
parentObject["res"] = parentArray;
} else {
console.log("date exists");
dateAndTimeObject = parentArray[tempIndex];
var timeArray = dateAndTimeObject["time"];
if(timeArray.length<5) timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
}
console.log("final res :: " + JSON.stringify(parentObject));
}
});});
Related
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;
}
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;
}
}
I'm a beginner in java script a trying a little program that parse data from a text file. In order to create a filter on a particular date i have made a function to get the date from and to that the user have enter. And the date a have to compare if it is in the range is in the text file, this date also i got it. But now i don't want to re-write the function "getAllFilesFromFolder" found in the code below, this function must be executed in all case but if i click on the button filter by by date it must read on the files with the date in range given by the user. Can someone give me an explanation on how to do it. i have tried the code below.
function getdate(){
var dateStart = new Date($('#dateStart').val()).getTime();
var dateEnd = new Date($('#dateEnd').val()).getTime();
//if(!testDate){var testDate = new Date(2014, 05, 02).getTime();}
var testDate = new Date(2014, 05, 02).getTime();
if (dateStart <= testDate && testDate <= dateEnd) {
alert('IN');
//Here filter the files with the date
}else{
alert('OUT');
//Here no new to read and parse the file beacause it is out of range
}
}
//Parse folder and file to get the required files
function getAllFilesFromFolder(folder){
//Parsing the given folder the result which is return is kept in an array
var test = fse.readdirSync(folder);
//Going through the array
for(var n=0; test[n]; n++){
var stats = fs.lstatSync(folder+"\\"+test[n]);
if(stats && stats.isDirectory()){
getAllFilesFromFolder(folder+"\\"+test[n]);
var path = folder+"\\"+test[n]+"<br />";
}else{
var path = folder+"\\"+test[n];
//Regex on the file to be taken
var pattern = /^(PM)[0-9]{5}[_](xam)[_](pmbok5th)[_](pmp)[_](v92)(.txt)$/;
var parent = folder+"\\";
var file = test[n];
var load = pattern.test(file);
//Split on file to get the "id user"
identifiant = file.split('_');
//Test the regex on file name "PM*_xam_pmbok5th_pmp_v92.txt"
if(load == true){
var read = fse.readFileSync(path, 'utf8');
var suspendDate = read.lastIndexOf('xam/');
var wantedDate = read.slice(suspendDate);
info = wantedDate.split('/');
var suspendData = read.lastIndexOf('/DB');
var suspendData = wantedDate.lastIndexOf('/DB');
var wantedData = wantedDate.slice(suspendData);
var db_response = wantedData.split(".");
var all_response = db_response[0].split(":");
if(typeof(info[2]) != "undefined" && all_response != "undefined"){
var response = all_response[1].split("|");
//Parsing the array response to find the "id" here id of the question and the "ans" here answer of the question "R" or "W"
for(var p = 0; p < response.length; p++){
//Test if result exist we increment if not it is generate with the function initResp
if(typeof(response[p]) != "undefined"){
var id = response[p].slice(0,6);
var ans = response[p].slice(-1);
if (question[id]) {
question[id][ans] += 1;
} else {
var results = initResp(ans);
question[id] = results;
};
} else {
}
}
} else {
//$("#results1").append("<strong>La session est vide</strong><br>");
}
i++;
}
}
}
};
I found a solution to my problem. See the code below for more information
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;
}
}
function getAllFilesFromFolder(folder)/*, useDate*/{
//Parsing the given folder the result which is return is kept in an array
var test = fse.readdirSync(folder);
//Going through the array
for(var n=0; test[n]; n++){
var stats = fs.lstatSync(folder+"\\"+test[n]);
if(stats && stats.isDirectory()){
getAllFilesFromFolder(folder+"\\"+test[n]);
var path = folder+"\\"+test[n]+"<br />";
}else{
var path = folder+"\\"+test[n];
//Regex on the file to be taken
var pattern = /^(PM)[0-9]{5}[_](xam)[_](pmbok5th)[_](pmp)[_](v92)(.txt)$/;
var parent = folder+"\\";
var file = test[n];
var load = pattern.test(file);
//Split on file to get the "id user"
identifiant = file.split('_');
//Test the regex on file name "PM*_xam_pmbok5th_pmp_v92.txt"
if(load == true){
var read = fse.readFileSync(path, 'utf8');
var suspendDate = read.lastIndexOf('xam/');
var wantedDate = read.slice(suspendDate);
var info = wantedDate.split('/');
testDate = new Date(info[4]).getTime();
rangeDate(testDate);
if(date == true){
var suspendData = read.lastIndexOf('/DB');
var suspendData = wantedDate.lastIndexOf('/DB');
var wantedData = wantedDate.slice(suspendData);
var db_response = wantedData.split(".");
var all_response = db_response[0].split(":");
if(typeof(info[2]) != "undefined" && all_response != "undefined"){
var response = all_response[1].split("|");
//Parsing the array response to find the "id" here id of the question and the "ans" here answer of the question "R" or "W"
for(var p = 0; p < response.length; p++){
//Test if result exist we increment if not it is generate with the function initResp
if(typeof(response[p]) != "undefined"){
var id = response[p].slice(0,6);
var ans = response[p].slice(-1);
if (question[id]) {
question[id][ans] += 1;
} else {
var results = initResp(ans);
question[id] = results;
};
} else {
}
}
} else {
//$("#results1").append("<strong>La session est vide</strong><br>");
}
i++;
}else{
}
}
}
}
};
I have found similar threads about this but I cant seem to make their solutions work for my specific issue. I currently have a calendar that will highlight the starting date of an Event. I need to change this to highlight the Start Date through the End Date.
Note: I did not write this code. It seems like whoever wrote this left a lot of junk in here. Please don't judge.
attachTocalendar : function(json, m, y) {
var arr = new Array();
if (json == undefined || !json.month || !json.year) {
return;
}
m = json.month;
y = json.year;
if (json.events == null) {
return;
}
if (json.total == 0) {
return;
}
var edvs = {};
var kds = new Array();
var offset = en4.ynevent.getDateOffset(m, y);
var tds = $$('.ynevent-cal-day');
var selected = new Array(), numberOfEvent = new Array();
for (var i = 0; i < json.total; ++i) {
var evt = json.events[i];
var s1 = evt.starttime.toTimestamp();
var s0 = s1;
var s2 = evt.endtime.toTimestamp();
var ds = new Date(s1);
var de = new Date(s2);
var id = ds.getDateCellId();
index = selected.indexOf(id);
if (index < 0)
{
numberOfEvent[selected.length] = 1;
selected.push(id);
}
else
{
numberOfEvent[index] = numberOfEvent[index] + 1;
}
}
for (var i = 0; i < selected.length; i++) {
var td = $(selected[i]);
if (td != null) {
if (!(td.hasClass("otherMonth"))){
td.set('title', numberOfEvent[i] + ' ' + en4.core.language.translate(numberOfEvent[i] > 1 ? 'events' : 'event'));
td.addClass('selected');
}
}
}
},
Instead of trying to select them all, I recommend you iterate over them instead. So something like this:
function highlightDates(startDate, endDate) {
var curDate = startDate;
var element;
$('.selected').removeClass('selected'); // reset selection
while (curDate <= endDate) {
element = getElementForDate(curDate)
element.addClass('selected');
curDate.setDate(curDate.getDate() + 1); // add one day
}
}
function getElementForDate(someDate) {
return $('#day-' + someDate.getYear() + "-" + someDate.getMonth() + "-" + someDate.getDay());
}
I am trying to build out an object that contains the NFL's 2012 schedule. I found a CSV of it online and can parse through it ok except for when I am trying to add games to each week. When I console log the schedule after the code executes each week only get one game (the last one) instead of the 16 (or so, depending on byes) they should have.
Note: Normally I put my prototypes in a source file instead of here but for clarity I included them.
BONUS: I'll post the object when it is complete. : D
Here's my code:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.capitalize = function() {
return this.substr(0, 1).toUpperCase() + this.substr(1);
}
Object.prototype.getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
var AppController = {};
//create a schedule object
AppController.Schedule = {};
var schedule = AppController.Schedule;
var scheduleArray = nflschedule.split(":::");
//set a game count so we can give each game an id
var gameCount = -1;
for(var i=0; i<scheduleArray.length; i++) {
gameCount++;
//filter out first line
if (i>0) {
//get a game
var thisGameItems = scheduleArray[i].split(",");
//game date
var gameDate = thisGameItems[0];
//week number
var colonSplitPattern = new RegExp("^[^:]+(?=:)");
var weekNumPattern=new RegExp("\Week(.*)");
var weekNum = "Week" + thisGameItems[2].match(colonSplitPattern).toString().match(weekNumPattern)[1].trim();
//get teams and game day
var homeTeam = thisGameItems[thisGameItems.length-3].trim();
var visitingTeam = thisGameItems[thisGameItems.length-2].trim();
var weekDay = thisGameItems[thisGameItems.length-1].trim().capitalize();
//check Schedule and see if we have this weekNum as key, if not add it
var gameWeeks = schedule.getKeys();
if (gameWeeks.contains(weekNum) == false) {
schedule[weekNum] = {};
}
var thisWeeksGames = schedule[weekNum];
//add games to the game week
thisWeeksGames[gameCount] = {
GameDate: gameDate,
GameWeek: weekNum,
HomeTeam: homeTeam,
VisitingTeam: visitingTeam,
GameDay: weekDay,
HomeTeamScore : "",
VistingTeamScore : ""
}
}
}
console.log(schedule);