How can I auto-complete an input date using JavaScript?
Like for example I input 5/2 it'll automatically be 20190502
function dateManagement(dateValue) {
var inputs = dateValue.split('/');
var month = (inputs[0].length == 1) ? '0' + inputs[0] : inputs[0];
var date = (inputs[1].length == 1) ? '0' + inputs[1] : inputs[1];
return new Date().getFullYear() + '' + month + '' + date;
}
function setupLevel1ItemDateManagementEditFunction(dateValue){
addLoadEvent(initLevel1ItemDateManagementEditFunction(dateValue));
}
function initLevel1ItemDateManagementEditFunction(dateValue){
return function(){
var dateVal = disp.getElement(dateValue);
addEventHandler(dateVal ,"onkeydown", function(e){
if(e.keyCode == KEY_ENTER){
var input = disp.get(dateValue);
var edited = "";
try{
edited = dateManagement(dateValue);
} catch(e){
console.log(e);
}
if(edited != "" && edited !=null){
disp.set(dateValue, edited);
}
}
return true;
});
return true;
};
}
i have tried reading a lot of threads and forums and i still dont get it.
i am completely new to coding so pls bear with me.
This is a very bad approach to set a date. But if you really needs to do this, you can use following function.
function getFullDate(yourInputText) {
var inputs = yourInputText.split('/');
var month = (inputs[0].length == 1) ? '0' + inputs[0] : inputs[0];
var date = (inputs[1].length == 1) ? '0' + inputs[1] : inputs[1];
return new Date().getFullYear() + '/' + month + '/' + date;
}
console.log(getFullDate('5/2')); //output: '2019/05/02'
Note:
new Date().getFullYear() will give you the current year.
Related
I am fairly new in NodeJS, and I am trying to build an event management system where the user can see events that are happening now, upcoming events and past events. I have built a model called events which has attributes startDate and endDate which a user selects upon creation of an event. I need to list events that are happening in the present, this is the function I have built so far, however, it doesn't work and I am pretty sure there is some mistakes in the syntax too. I would really appreciate anyone's help on this :)
exports.listPresent = async (req, res) => {
try {
const event = await Event.find({})
const eventPresent = [];
for (let i = 0; i < event.length; i++) {
var dateArr = event[i].startDate.toString().split("-");
var dateArr2 = event[i].endDate.toString().split("-");
var inputDate = new Date('"' + dateArr[2] + "-" + dateArr[1] + "-" + dateArr[0] + '"').setHours(0, 0, 0, 0);
var inputDate2 = new Date('"' + dateArr2[2] + "-" + dateArr2[1] + "-" + dateArr2[0] + '"').setHours(0, 0, 0, 0);
var toDay = new Date().setHours(0, 0, 0, 0);
if (event[i].startDate != null && event[i].startDate != '' && event[i].endDate !=null && event[i].endDate != '') {
if(inputDate == toDay || (inputDate >= toDay && inputDate <= inputDate2)){
eventPresent.push(i);
}
}
return eventPresent;;
}
} catch (error) {
res.status(500).json( { error: error.message });
}
};
I tried writing a function (the one above) but I am new at JavaScript and I am a bit lost on how to make this work.
The logic is correct in this one, you just need to replace return eventPresent to res.status(200).json(eventPresent) - and put this outside the for loop, and also eventPresent.push(i) with eventPresent.push(event[i]), as you are only pushing the index into the array, and not the actual element as such:
exports.listPresent = async (req, res) => {
try {
const event = await Event.find({})
const eventPresent = [];
for (let i = 0; i < event.length; i++) {
var dateArr = event[i].startDate.toString().split("-");
var dateArr2 = event[i].endDate.toString().split("-");
var inputDate = new Date('"' + dateArr[2] + "-" + dateArr[1] + "-" + dateArr[0] + '"').setHours(0, 0, 0, 0);
var inputDate2 = new Date('"' + dateArr2[2] + "-" + dateArr2[1] + "-" + dateArr2[0] + '"').setHours(0, 0, 0, 0);
var toDay = new Date().setHours(0, 0, 0, 0);
if (event[i].startDate != null && event[i].startDate != '' && event[i].endDate !=null && event[i].endDate != '') {
if (inputDate == toDay || (inputDate >= toDay && inputDate <= inputDate2)){
eventPresent.push(event[i]);
}
}
}
res.status(200).json(eventPresent);
} catch (error) {
res.status(500).json( { error: error.message });
}
};
Hope this helps! :)
I have a datatable and using moment for filtering date. My problem is if i enter days before day 12 is working fine but after day 12 not filtering my data. For example the date between 01/01/2021 and 12/01/2021 is working fine but if i enter 01/01/2021 and 13/01/2021 not getting any data.
// Extend dataTables search
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#min-date').val();
var max = $('#max-date').val();
var createdAt = data[0] || 0; // Our date column in the table
moment().format('DD/MM/YYYY');
if (
(min == "" || max == "")
||
(moment(createdAt, 'DD/MM/YYYY').isSameOrAfter(min, 'DD/MM/YYYY') && moment(createdAt, 'DD/MM/YYYY').isSameOrBefore(max, 'DD/MM/YYYY'))
) {
return true;
}
return false;
}
);
function dtConvFromJSON(data) {
if (data == null) return '1/1/1950';
var r = /\/Date\(([0-9]+)\)\//gi
var matches = data.match(r);
if (matches == null) return '1/1/1950';
var result = matches.toString().substring(6, 19);
var epochMilliseconds = result.replace(
/^\/Date\(([0-9]+)([+-][0-9]{4})?\)\/$/,
'$1');
var b = new Date(parseInt(epochMilliseconds));
var c = new Date(b.toString());
var curr_date = c.getDate();
var curr_month = c.getMonth() + 1;
var curr_year = c.getFullYear();
var curr_h = c.getHours();
var curr_m = c.getMinutes();
var curr_s = c.getSeconds();
var curr_offset = c.getTimezoneOffset() / 60
var d = curr_date.toString() + '/' + curr_month.toString() + '/' + curr_year.toString();
return d;
}
Iam using dtConvFromJson function here ;
"columns": [
{ "data": "Date", render: function (data, type, full) { return dtConvFromJSON(data); }, "autoWidth": true },
I fixed to problem.
I have changed my function dtConvFromJSON(data) function to
function dtConvFromJSON(data) {
return new Date(parseInt(data.replace('/Date(', '')))
}
and voila! Works now!
I want to highlight overdue task when refresh page and when click on add task button such as the code below:
$(document).ready(function(){
$('.add-task').on('click',function(){
$('.task-date').each(function(){
var a = new Date().dateFormat('dd/mm/yy').getTime();
var b = formatDate(b,'dd/mm/yy').getTime();
var task = new Date($('.task-date')).getTime();
if(task < b) {
return $('todo-task').addClass('overdue');
}
});
});
});
I tried some other ways but still not working so please check JSFiddle here and source site here and help me. Thank you.
var generateElement = function(params){
var parent = $(codes[params.code]),
wrapper;
if (!parent) {
return;
}
var curDate=new Date();
var overDueClass="";
if(params.date<curDate){ // Check the current date is less than to-do date here
overDueClass=" overdue";
}
wrapper = $("<div />", {
"class" : defaults.todoTask+overDueClass,
"id" : defaults.taskId + params.id,
"data" : params.id
}).appendTo(parent);
.....................
...............
}
For solve your task no need to create new functions. You may just apply the logic in generateElement function in your todo.js file.
var d = new Date();
var date = d.getDate() + "/" + d.getMonth()+1 + "/" + d.getFullYear();
var overDueClass= "";
// Add Task
var generateElement = function(params){
var parent = $(codes[params.code]),
wrapper;
if (!parent) {
return;
}
// Check the current date is less than to-do date.
if(params.date < date) {
overDueClass= "overdue";
} else {
overDueClass="";
};
wrapper = $("<div />", {
"class" : defaults.todoTask+" "+overDueClass,
"id" : defaults.taskId + params.id,
"data" : params.id
}).appendTo(parent);
I'm having an issue with calling a JavaScript function while in the codebehind method:
This code populates the textboxes with the cookieValues data. The JavaScript CalculateDOBAge gets called and does an existing DOB calculation and determines if the Age being returned is the same age as the DOB being returned.
However, if it determines that the DOB calculates a different Age then what is being returned I want to clear out the txtDOB and txtMonths textboxes. This is the part that isn't working.
ASP.Net Code Behind:
private void LoadSheetValues()
{
txtDOB.Text = cookieValues["DOB"];
txtAge.Text = cookieValues["Age"];
txtMonths.Text = cookieValues["Months"];
ClientScript.RegisterStartupScript(GetType(), "CalculateDOBAge", "calcDOBAge()", true);
}
JavaScript snippet:
if ((displayYear == age) && (displayMonth == months)) {
//The SAME
} else {
//Different
document.getElementById("txtDOB").value = '';
document.getElementById("txtMonths").value = '';
}
The javascript code is called from the ClientScript.RegisterStartupScript call and I can step through the values being blanked out. However, I think I dealing with a page lifecycle issue as when I check the screen after completion, the values remain in the textboxes.
I need the RegisterStartupScript (vs RegisterClientScriptBlock) as the CalculateDOBAge function needs the elements to be available and populated (so I can do the DOB calculation).
Is there a way to set this up using the RegisterStartupScript to return a True/False and then I can continue in the codebehind to clear out the textbox text?
Unfortunately this is an ancient application and jQuery or any modern frameworks are not available.
Full JavaScript:
function DOBAgeMonthCheck(birthDate, dateFormat) {
try {
if (dateFormat == 'MMDD') {
var bmo = birthDate.substr(0, 2);
var bday = birthDate.substr(3, 2);
var byr = birthDate.substr(6, 4);
} else if (dateFormat == 'DDMM') {
var bmo = birthDate.substr(3, 2);
var bday = birthDate.substr(0, 2);
var byr = birthDate.substr(6, 4);
} else if (dateFormat == 'YMD') {
var byr = birthDate.substr(0, 4);
var bmo = birthDate.substr(5, 2);
var bday = birthDate.substr(8, 2);
}
//replaces *ALL* "_" with ""
byr = byr.replace(/_/g, "");
bmo = bmo.replace(/_/g, "");
bday = bday.replace(/_/g, "");
var yrDiff;
var displayMonth;
var displayYear;
var now = new Date();
tday = now.getDate();
tmo = now.getMonth() + 1; //January is 0!
tyr = now.getFullYear();
//set four digit year
var tmpYr = tyr.toString();
byr = removeLeadingZero(byr);
var tmpLength = byr.length;
if (tmpLength < 4) {
if (byr > tmpYr.substr(2, 2))
byr = "1900".substr(0, 4 - tmpLength) + byr;
else
byr = "2000".substr(0, 4 - tmpLength) + byr;
}
if ((tmo > bmo) || (tmo == bmo & tday >= bday))
yrDiff = parseInt(byr)
else
yrDiff = parseInt(byr) + 1
if (tyr - yrDiff < 0)
displayYear = 0;
else
displayYear = (tyr - yrDiff);
if (tmo >= bmo)
displayMonth = tmo - parseInt(bmo);
else
displayMonth = 12 - (parseInt(bmo) - tmo);
var age;
var months;
try { age = document.getElementById("txtAge").value; } catch (err) { }
try { months = document.getElementById("txtMonths").value; } catch (err) { }
if ((displayYear == age) && (displayMonth == months)) {
//The SAME
} else {
//Different
document.getElementById("txtDOB").value = '';
document.getElementById("txtMonths").value = '';
}
}
catch (err) { }
}
I'm getting to the //Different section and watching the values being cleared.
I am running a DOM script and it is working PERFECTLY in Chrome and Firefox, but not IE8 or 9. The error messages in IE that I get are
document.getElementByld(..) is null or not an object
Object doesn't support this property or method
Unable to set value of the property 'innerHTML': object is null or undefined (URL: http://twitter.com/javascripts/blogger.js)
Code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
// DOM Ready
$(function() {
$.getJSON('http://twitter.com/status/user_timeline/LaunchSeven.json?count=2&callback=?', function(data){
$.each(data, function(index, item){
$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p><strong>' + relative_time(item.created_at) + '</strong></p></div>');
});
});
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
}
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
});
</script>
Thank you in Advance,
Adam
Your page needs to have an element with the ID twitter_update_list...
document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
Can't say why it isn't available in IE without seeing more code.
Second argument. That's a function definition and not a function being fired. but if m.link(m) didn't work by itself, executing the function properly wouldn't work either.
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
So just make the second arg m.link(m) (no semi)
I'm not sure this explains your document.getElementById issue though. But it might be causing a bug cascade somewhere.
Also, you should really define that string prototype before everything else. I believe only named functions hoist e.g. function someName(){.. vs. var someName = function(){...