Formatting an user input date. - javascript

Is there a better way to format a date imputed by a user. I have an input field where when clicked on a calender pops up and you can chose a date but the user also has the option to type in the date. I want the user to be able to type in 1/12 and my javascript to format it to 01/12/2012. Is there an easy way to go about this with out having to do all types of checks? If not what is the best way to go about this?

I've just gave it a try but not sure if it's the proper way but I think it's working (month/day/year).
$('input[name="txt_date"]').on('blur', function(e){
var dt=$(this).val();
if(dt!='')
{
if(dt.indexOf('/'))
{
var da=dt.split('/');
var l=da.length;
if(l <= 3)
{
var date='';
for(i=0;i<l;i++)
{
if(i==0)
{
if(da[i].match(/^\d{1}|d{2}$/) && da[i]>0 && da[i]<=12)
{
var m=da[i].length==1 ? '0'+da[i] : da[i];
date=m;
}
}
if(i==1)
{
if(da[i].match(/^\d{1}|d{2}$/) && da[i]>0 && da[i]<=31)
{
var d=da[i].length==1 ? '0'+da[i] : da[i];
date+='/'+d;
}
}
if(i==2)
{
if(da[i].match(/^\d{4}$/))
{
date+='/'+da[i];
}
else date+='/'+new Date().getFullYear();
}
}
if(l<3)
{
date+='/'+new Date().getFullYear();
}
if(date.match(/^\d{2}\/\d{2}\/\d{4}$/))
{
$(this).val(date);
}
else alert('invalid date!');
}
}
}
});
DEMO.

This library could help you: http://www.datejs.com/
dd/mm/yyyy is a valid format e.g. in Spain, UK, ...

Here's what I came up with.
var checkDate = function(dateVal, input){
if(dateVal.length == 10){
return;
}
var d = new Date();
var currentMonth = d.getMonth();
var year = d.getFullYear();
var firstIndex = dateVal.indexOf('/');
var month = parseInt(dateVal.substr(0, firstIndex));
var day = parseInt(dateVal.substr(firstIndex + 1, 2));
if(month < 10){
month = '0' + month;
}
if(day < 10){
day = '0' + day;
}
if(month > currentMonth){
year = year - 1;
}
dateVal = month + '/' + day + '/' + year;
if(isNaN(month)){
input.val('');
return;
}
input.val(dateVal);
};

Related

Equivalent of arrow functions for IE

I wrote a program that works well in Google Chrome, but I just realized that it is having problems in IE. IE states that this is due to a syntax error given by the use of arrow functions since they are not supported in the latest IE. Can anyone tell me how to change my code to be able to run it on IE?
function removeRow(a, ref, plt, pcs, loc, trk, din) {
var pro;
swal("Enter the shipment's tracking information:", {
content: "input",
buttons: {
cancel: true,
roll: {
text: "Don't have it",
value: " ",
},
confirm: {
text: "Submit",
}
}
})
.then((value) => {
pro = value;
//console.log(pro);
if (pro !== null || pro === ' ') {
b = '#' + a;
c = '#H' + a;
var d = new Date();
var n = Math.round(d.getTime() / 1000);
var table = $('#mytable')
.DataTable();
// Remove a row by Id:
table.row(b)
.remove()
.draw();
var url = "delete.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: {
id: a,
track: pro,
dateout: n
},
success: function(data) {
//alert(data); // show response from the php script.
//console.log('Success!');
}
});
swal("Success", "Shipment was entered successfully!", "success");
if (ref == '') {
}
var t = $('#myhistory').DataTable();
t.row(c)
.remove()
.draw();
var reference = ref;
var pallets = plt;
var pieces = pcs;
var location = loc;
var carrier = trk;
var datein = din;
var dateout = n;
var rowid = 'H' + a;
if (datein.length < 12) {
var month = datein.toString().substring(0, 1);
if (month == '01') {
month = 'Jan';
} else if (month == '02') {
month = 'Feb';
} else if (month == '03') {
month = 'Mar';
} else if (month == '04') {
month = 'Apr';
} else if (month == '05') {
month = 'May';
} else if (month == '06') {
month = 'Jun';
} else if (month == '07') {
month = 'Jul';
} else if (month == '08') {
month = 'Aug';
} else if (month == '09') {
month = 'Sep';
} else if (month == '10') {
month = 'Oct';
} else if (month == '11') {
month = 'Nov';
} else if (month == '12') {
month = 'Dec';
}
var day = datein.toString().substring(1, 3);
var year = datein.toString().substring(3, 7);
var hour = datein.toString().substring(7, 9);
var second = datein.toString().substring(9, 11);
} else {
var month = datein.toString()
.substring(0, 2);
if (month == '01') {
month = 'Jan';
} else if (month == '02') {
month = 'Feb';
} else if (month == '03') {
month = 'Mar';
} else if (month == '04') {
month = 'Apr';
} else if (month == '05') {
month = 'May';
} else if (month == '06') {
month = 'Jun';
} else if (month == '07') {
month = 'Jul';
} else if (month == '08') {
month = 'Aug';
} else if (month == '09') {
month = 'Sep';
} else if (month == '10') {
month = 'Oct';
} else if (month == '11') {
month = 'Nov';
} else if (month == '12') {
month = 'Dec';
}
var day = datein.toString().substring(2, 4);
var year = datein.toString().substring(4, 8);
var hour = datein.toString().substring(8, 10);
var second = datein.toString().substring(10, 12);
}
var tout = new Date();
var timeout = tout.toString();
var monthout = tout.toString().substring(4, 7);
var dayout = tout.toString().substring(8, 10);
var yearout = tout.toString().substring(11, 16);
var hourout = tout.toString().substring(16, 18);
var secondout = tout.toString().substring(19, 21);
var dateout = monthout + ', ' + dayout + ' ' + yearout + ' at ' + hourout + ':' + secondout;
var datein = month + ', ' + day + ' ' + year + ' at ' + hour + ':' + second;
t.row.add([
reference,
pallets,
pieces,
location,
carrier,
datein,
dateout,
pro
])
.node()
.id = rowid;
t.draw(false);
}
});
}
I could be missing something, but after a quick skim of your code, only this line appears to use any ES6 syntax:
.then((value) => {
Simply change it to:
.then(function(value) {
If you have much more code and don't want to remove such references by hand, #jonrsharpe's suggestion of a transpiler is a good one.

show appointments/ dates of today with JavaScript function

I want to show the actual appointments of the day in my HTML. I would like to implement it with a JavaScript where I get the name of the appointment and the date out of an excel table.
I already wrote something but it doesn't work and not in the way I want it.
Code:
function appointment() {
var event = [];
var temp = [];
event[0] = ["17.12.2015", "test1"];
event[1] = ["11.12.2015", "TestToday"];
var datum = new Date();
var today = today.getDate();
var month = today.getMonth() + 1;
for (i = 0; i < event.length; i++) {
if (event[i]) {
if (event[i][0] == today && event[i][0] == month) {
event[i][0] = temp[i];
}
}
else {
break;
}
}
if (temp.length == 0) {
document.write("Today is nothing to do");
}
else {
var x2 = "Today " + ((temp.length == 1) ? "is following event: " : "are following events: ");
for (i = 0; i < temp.length; i++) {
x2 += ((temp[i] > 0) ? ((temp[i] == (temp.length - 1)) ? " and " : ", ") : " ") + temp[event[1]][3] + "(" + temp[event[i]][2] + ")";
}
document.write(x2 + " appointment");
}
}
Question: How can I make it work? How can I read the appointment toppic and date out of a excel table?
Change your code to
var datum = new Date().setHours(0,0,0,0);
//you don't need today and month
if (event[i]) {
eventDate = new Date(event[i][0].split(".").reverse()).getTime();
if (datum === eventDate) {
temp.push(event[i][1]); //there was a problem here as well
}
}
else {
break;
}
jsFiddle
Issue is in your for loop. To compare today's date should be in dd.mm.yy format as it is in array:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
dd='0'+dd;
if(mm<10)
mm='0'+mm;
var today = dd+'.'+mm+'.'+yyyy;
for (i = 0; i < event.length; i++) {
if (event[i]) {
if (event[i][0] == today) {
temp[i] = event[i][0];
}
}
// Don't break your for loop
}
Working Fiddle

javascript validate birthday

im trying to validate birth numbers with a simple script but this script returns true even tho i type in a month over 12 and day over 31, so what have i missed?
var as = /^[0-9]{6}[-+][0-9]{4}$/;
var pn=document.forms.kontakt.pnr.value;
if (as.test(pn)) {
var year = pn.substr(0,2);
var month = pn.substr(2,2);
var day = pn.substr(4,2);
if (month <= 13 && day <= 32) {
return true;
}
} else {
alert ("Fyll i korrekt personnummer xxxxxx-xxxx");
kontakt.pnr.style.background = "red";
return false;
}
The if/else statement is fine, the problem is probably in your substr or regex.
I would console.log your "month" and "day" variables to narrow down your bug.
var as = /^[0-9]{6}-[0-9]{4}$/;
var pn = document.forms.kontakt.pnr.value;
if (as.test(pn)) {
var year = pn.substr(0,2);
var month = pn.substr(2,2);
var day = pn.substr(4,2);
if (month > 12 || day > 31) {
alert("Fyll i korrekt personnummer"); siffror
kontakt.pnr.style.background = "red";
return false;
}
else {
return true;
}
}
else {
alert("Fyll i personnummer i formatet xxxxxx-xxxx");
kontakt.pnr.style.background = "red";
return false;
}
This was the solution for me!

How to disable specific dates in Magento Order Delivery Date extensions calendar

I want to disable specific dates in Magento Connect Order Delivery Date Calendar and tried many ways. But could not be successful. Below is my code. It says "TypeError: $.inArray is not a function" when click on the calendar icon.
disableFunc : function(date)
{
var day_off_array = dayoff.split(",") ;
currentTime = new Date();
var d1=currentTime.getDate();
var m1=currentTime.getMonth();
var y1=currentTime.getFullYear();
m1=m1+1;
var counter = 1;
var disabledDays =
["10-20-2013", "10-21-2013", "11-15-2013", "11-17-2013"];
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1) {
return [false];
}
}
return [true];
if(y < y1)
{
return true;
}
else if(m1 > m && y==y1)
{
return true;
}
}
and this is the original code.
disableFunc : function(date)
{
var y = calendar.date.getFullYear();
var m = calendar.date.getMonth();
var d = calendar.date.getDate();
var day_off_array = dayoff.split(",") ;
//document.write(day_off_array);
currentTime = new Date();
var d1=currentTime.getDate();
var m1=currentTime.getMonth();
var y1=currentTime.getFullYear();
var counter = 1;
for (var i=0; i<day_off_array.length;i++){
if (day_off_array[i]>=0 && day_off_array[i]!=''){
if (date.getDay()==day_off_array[i]){
if (date.getDate()==currentTime.getDate()){
test_flag=true;
}
return true;
}
}
}
if(y < y1)
{
return true;
}
else if(m1 > m && y==y1)
{
return true;
}
}
Any helps would be appreciated.
It's too late to answer the question, but this may help someone like me!
var disabledDays = ["10-20-2014", "10-21-2014", "11-15-2014", "11-17-2014"];
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
var dd = (m+1) + '-' + d + '-' + y;
if(disabledDays.indexOf(dd) != -1) {
return true;
}
}

How to validate Date in form onblur

function validatedate(inputText) {
var thsid = $(inputText).attr('id');
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
}
This is my common js method [incomplete] onblur="validatedate(this)" but its accepting invalid dates also
I have one datepicker in my jsp as textbox.onblur i need to validate date using javascript
these are the rules
mm/dd/yy format
mm should not exceed 31
dd should not exceed 12
should be commom method for all datepickers
if given input invalid ..should give an alert and empty datepicker..............
Change:
onblur="validatedate(this)"
To:
onblur="validatedate(this.value);"
this contains input DOM element itself and not the input's text value.
Also your validatedate() function appears to be doing nothing. There is no return value, no alert or anything to stop form processing. I take for granted you only supplied a snippet of the function itself.
Saidesh's answer got me most of the way to where I wanted, but I didn't like the JQuery dependency. I added a couple minor improvements as well as a fully functional test page.
<html>
<head>
<script type="application/javascript">
function validatedate(inputTextObject) {
// matches 11/12/2011 or 11-12-2011
var ret = true;
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
// Match the date format through regular expression
if (inputTextObject.value.trim() != "") {
if (inputTextObject.value.trim().match(dateformat)) {
// document.form1.text1.focus();
//Test which seperator is used '/' or '-'
var opera1 = inputTextObject.value.split('/');
var opera2 = inputTextObject.value.split('-');
lopera1 = opera1.length;
lopera2 = opera2.length;
// Extract the string into month, date and year
if (lopera1 > 1) {
var pdate = inputTextObject.value.split('/');
} else if (lopera2 > 1) {
var pdate = inputTextObject.value.split('-');
}
var mm = parseInt(pdate[0]);
var dd = parseInt(pdate[1]);
var yy = parseInt(pdate[2]);
// Create list of days of a month [assume there is a leap year by default]
var ListofDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (mm == 1 || mm > 2) {
if (dd > ListofDays[mm - 1]) {
alert('Invalid date format!');
inputTextObject.focus();
ret = false;
}
}
if (mm == 2) {
var lyear = false;
if ((!(yy % 4) && yy % 100) || !(yy % 400)) {
lyear = true;
}
if ((lyear == false) && (dd >= 29)) {
alert('Invalid date format!');
inputTextObject.focus();
ret = false;
}
if ((lyear == true) && (dd > 29)) {
alert('Invalid date format!');
inputTextObject.focus();
ret = false;
}
}
} else {
alert("Invalid date format!");
inputTextObject.focus();
ret = false;
}
if (ret == false) {
inputTextObject.style.color='red';
} else {
inputTextObject.style.color='blue';
}
}
return ret;
}
</script>
</head>
<body>
Date Test (<strong>mm/dd/yyyy</strong>): <input name="date_test" type="text" onblur="validatedate(this);" />
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAmAQMAAACS83vtAAAABlBMVEUAAAD///+l2Z/dAAAACXBIWXMAAAsTAAALEwEAmpwYAAAApElEQVQI1y3OQWpCMQBF0ZtnqF8Q286FCm7CgdgsqUv44qBuqvKXEqgLiCIokuY5qGcFJxiwcABxJoEHXhseedTkKQeony5NNdH1FLtuFEDofPc2i2sbeh0hl0jZgzoiKw1vPQhYICZKiJfQI4CFSFyyDA2FjFCCgm5fHLvIjWGs+Zo94fdvvnScOW74/6jbfdf0XClz4rnl530KLnw0XHELBvwAwg1K5dfpv8IAAAAASUVORK5CYII=" />
</body>
</html>
Now my method is ready..with the help of stackoverflow:
function validatedate(inputText)
{
var thsid=$(inputText).attr('id');
var classname=$(inputText).attr('class');
var classstr=classname.split(" ");
var ret=true;
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
// Match the date format through regular expression
if(inputText.value.trim()!="")
{
if( inputText.value.trim().match(dateformat))
{
// document.form1.text1.focus();
//Test which seperator is used '/' or '-'
var opera1 = inputText.value.split('/');
var opera2 = inputText.value.split('-');
lopera1 = opera1.length;
lopera2 = opera2.length;
// Extract the string into month, date and year
if (lopera1>1)
{
var pdate = inputText.value.split('/');
}
else if (lopera2>1)
{
var pdate = inputText.value.split('-');
}
var mm = parseInt(pdate[0]);
var dd = parseInt(pdate[1]);
var yy = parseInt(pdate[2]);
// Create list of days of a month [assume there is no leap year by default]
var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
if (mm==1 || mm>2)
{
if (dd>ListofDays[mm-1])
{
alert('Invalid date format!');
$(inputText).focus();
inputText.value="";
ret=false;
return false;
}
}
if (mm==2)
{
var lyear = false;
if ( (!(yy % 4) && yy % 100) || !(yy % 400))
{
lyear = true;
}
if ((lyear==false) && (dd>=29))
{
alert('Invalid date format!');
$('#'+thsid).focus();
inputText.value="";
ret=false;
return false;
}
if ((lyear==true) && (dd>29))
{
alert('Invalid date format!');
$('#'+thsid).focus();
inputText.value="";
ret=false;
return false;
}
}
}
else
{
alert("Invalid date format!");
$('#'+thsid).focus();
inputText.value="";
ret=false;
return false;
}
}

Categories