Convert Date from one format to another format in JavaScript - javascript

I have a string of a date in javascript in format #1. I need to convert it to format #2.
The problem starts when one format is "dd/mm/yy" and the other is "mm/dd/yy".
The formats change dynamically and I have the formats as strings, but I need a function like
Date newDate = convert(currentDate, currentFormatString, newFormatString).
How can I do it?

You should look into momentjs, which is a javascript date/time library. With that, you can easily convert between dates of different format. In your case, it would be:
string newDate = moment(currentDate, currentFormatString).format(newFormatString)
For example, moment("21/10/14", "DD/MM/YY").format("MM/DD/YY") would return "10/21/14"

You can use the above described answer of momnet.js or the function below for splitting and using it
For using moment.js make sure you enter your old and new format in upper case
function parseDate(strDate) {
var dateFormat = $('#currentDateFormat').val();
var str;
var res;
var strFormat = dateFormat.split('.');
if (strFormat.length != 3)
strFormat = dateFormat.split('/');
if (strFormat.length != 3)
strFormat = dateFormat.split('-');
str = strDate.split('.');
if (str.length != 3)
str = strDate.split('/');
if (str.length != 3)
str = strDate.split('-');
if (strFormat[0].substr(0, 1) == 'd' && strFormat[1].substr(0, 1) == 'M' &&
strFormat[2].substr(0, 1) == 'y') // for dd MM yyyy
res = new Date(str[2], str[1], str[0]);
if (strFormat[0].substr(0, 1) == 'M' && strFormat[1].substr(0, 1) == 'd' &&
strFormat[2].substr(0, 1) == 'y') // for MM dd yyyy
res = new Date(str[2], str[0], str[1]);
if (strFormat[0].substr(0, 1) == 'y' && strFormat[1].substr(0, 1) == 'M' &&
strFormat[2].substr(0, 1) == 'd')
res = new Date(str[0], str[1], str[2]);
if (strFormat[0].substr(0, 1) == 'y' && strFormat[1].substr(0, 1) == 'd' &&
strFormat[2].substr(0, 1) == 'M')
res = new Date(str[0], str[2], str[1]);
return res;
}

You can use the function below
console.log(changeDateFormat('12/1/2020','dd/MM/yyyy','MM/dd/yyyy'));
function changeDateFormat(value, inputFormat, outputFormat) {
let outputSplitter = "/";
let strOutputFormat = outputFormat.split(outputSplitter).map(i => i.toUpperCase());
if (strOutputFormat.length != 3) {
strOutputFormat = outputFormat.split('-');
outputSplitter = '-';
}
if (strOutputFormat.length != 3) throw new Error('wrong output format splitter :(');
let date = null;
if (value instanceof Date) {
date = {
["YYYY"]: value.getUTCFullYear(),
["MM"]: value.getMonth() + 1,
["DD"]: value.getDate()
}
}
if (typeof value == 'string') {
let inputSplitter = "/";
var strInputFormat = inputFormat.split(inputSplitter).map(i => i.toUpperCase());
if (strInputFormat.length != 3) {
strInputFormat = inputFormat.split('-');
inputSplitter = '-';
}
if (strInputFormat.length != 3) throw new Error('wrong input format splitter :(');
let dateElements = value.split(inputSplitter);
if (dateElements.length != 3) throw new Error('wrong value :(');
date = {
[strInputFormat[0]]: dateElements[0],
[strInputFormat[1]]: dateElements[1],
[strInputFormat[2]]: dateElements[2],
}
}
if (!date) throw new Error('unsupported value type:(');
let result = date[strOutputFormat[0]] + outputSplitter
+ date[strOutputFormat[1]] + outputSplitter
+ date[strOutputFormat[2]];
return result;
}

It seems that you should use the library of query-dateformat git hub for jquery-dateformat
or you can use the normal function like date-time-formate, use the library to config the formate template

Related

Format DD/MM/YYYY in reactjs on Input Change

I want to add "/" when user enters in a input field after dd/mm/yyyy, basically user is trying to enter DOB, and want '/' to be automatically added after entering dd then mm then yyyy.
Also User wont be able to input more than 31 in dd & 12 in mm and for the year need to check if the DOB is invalid, in case of Leap year (example 29/02/2024) and not more than 4 digits.
I tried but when user enters text after 2 characters '/' is entered but the input is somehow lost. for example when user types '22' then '2', so only '22/' is shown not the 2.
Also i did tried the logic for the leap year but somehow managing the overall state in single input field is not working.
Here is what I tried.
import { useCallback, useState } from "react";
import moment from "moment";
import "./styles.css";
export default function App() {
const [dob, setDob] = useState("");
const [day, setDay] = useState("");
const [month, setMonth] = useState("");
const [year, setYear] = useState("");
const m = moment();
const [errors, setErrors] = useState();
const onchange = (e) => {
setDob(e.target.value);
checkAndAdd();
};
const handleDate = async () => {
let dayOfDob, monthOfDob, yearOfDob;
yearOfDob = dob.substring(6, 10);
if (dob.length === 2) {
dayOfDob = dob.substring(0, 2);
if (dayOfDob > 31) {
setErrors({ ...errors, dayO: "Day is greater" });
}
setDay(dayOfDob);
} else if (dob.length === 5) {
monthOfDob = dob.substring(3, 5);
if (monthOfDob > 12) {
setErrors({ ...errors, monthO: "Month is greater" });
}
setMonth(monthOfDob);
}
if (yearOfDob.length <= 4) {
let res = await isValidDate(dayOfDob, monthOfDob, yearOfDob);
console.log("validateDate", res);
}
};
const isValidDate = async (dayValue, monthValue, yearValue) => {
if (dayValue && monthValue && yearValue) {
let dayVal = dayValue.trim();
let monthVal = monthValue.trim();
const yearVal = yearValue.trim();
let leapYear = false;
if (dayVal != "" && monthVal != "" && yearVal != "") {
dayVal = dayVal <= 9 ? "0" + Number(dayVal) : dayVal;
monthVal = monthVal <= 9 ? "0" + Number(monthVal) : monthVal;
const d = new Date(yearVal + "-" + monthVal + "-" + dayVal);
if (yearVal % 4 !== 0 && monthVal == 2 && dayVal > 28) {
leapYear = true;
}
if (monthVal == 2 && dayVal > 29) {
leapYear = true;
}
if (yearVal.length === 4) {
if (!isNaN(d.getTime()) && !leapYear) {
setErrors("");
return d;
} else {
setErrors("DOB format is invalid");
return false;
}
}
} else {
return false;
}
}
};
const checkAndAdd = useCallback(() => {
if (dob.length === 2 || dob.length === 5) {
setDob(`${dob}/`);
handleDate();
}
}, [dob]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<input type="text" value={dob} onChange={onchange} />
</div>
);
}
Please let me know if explained it correctly.
Also working sandbox is here
Thanks.
To solve your problem of the number being replaced by a "/" you can simply do something like this on your onchange() and checkAndAdd() methods :
const onchange = (e) => {
const value = e.target.value;
setDob(value);
checkAndAdd(value);
};
const checkAndAdd = useCallback((value) => {
if (dob.length === 2 || dob.length === 5) {
const last = value.charAt(value.length - 1);
setDob(`${dob}/${last}`);
handleDate();
}
}, [dob]);
So I just had to do this for a non-React legacy site using jQuery but the approach is easily adapted. Here is how to do it in jQuery (I don't have time at the moment to rewrite it but it's mostly vanilla JavaScript):
$("#dob").bind("keyup", function(event) {
var value = event.target.value.replace(/[^0-9\/]/g, "").replace(/\/\/+/g, '/').trim();
if (priorValue !== null && priorValue.length < event.target.value.length && value.length > 1) {
const parts = value.split("/");
const month = parts[0];
const day = parts[1];
const year = parts[2];
if (value.length === 2 && value.indexOf("/") === -1) {
// "10" -> "10/"
event.target.value = value + "/";
} else if (value.length === 5 && parts.length !== 3) {
// "12/34" -> "12/34/"
event.target.value = value + "/";
} else if (value.length === 4 && value.charAt(1) === "/" && !value.charAt(3) === "/") {
// "1/15" -> "1/15/"
// but not "1/1/" -> "1/1//"
event.target.value = value + "/";
} else if (parts.length > 3 && value[value.length - 1] === "/") {
// "1/15/1950/" -> "1/15/1950"
event.target.value = value.slice(0, -1);
} else if (parts.length === 3 && year.length > 4) {
// "1/15/19501" -> "1/15/1950"
// avoiding slicing month and day w/ .slice(0, 2) for now...
event.target.value = month + "/" + day + "/" + year.slice(0, 4);
} else if (value !== event.target.value) {
event.target.value = value;
}
}
priorValue = event.target.value;
});
There are a bunch of gotchas like some event types not working on Android (although synthetic events in React might solve that for you). Also, I suggest setting HTML5 input hint to numeric on the field with inputmode="numeric" which will default mobile to numeric input.
I check the length and if it's shorter than the prior length in order to handle backspace/deleting.
It's not perfect but it's working fairly well. I think there might be better methods like defaulting to a date input on desktop and doing an iOS-style date spinner but that is a fair amount of work (or you can pay for it, there are actually commercial solutions which seems excessive but there you go).

Date Evaluation in JS

I need to validate a credit card expiry date, I have the javascript code but I don't know how to customize it for my need.
this is my code, I only need the date in a mm/yy format but this code has the date format in mm/dd/yyyy.
var date = document.getElementById('date');
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0))
&& num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
date.addEventListener('input', function(e) {
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12);
if (values[1]) values[1] = checkValue(values[1], 31);
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
this.value = output.join('').substr(0, 14);
});

Cannot read property 'split' of undefined using calendar

I am working on calendar with js in my project for availabilities it works correctly. but when I have a record which has a start date equal an end date.
for add event to my calendar i'm using this push:
listDate.push({startDate :strDate, endDate : enDate});
in my script datetimepicker this is function isAvailable
isAvailable: function(date, month, year) {
for (var i in this.unavailable) {
var book_date = this.unavailable[i].startDate.split("-");
if (book_date.length !== 3) {
return false;
} else if (
(book_date[0] == "*" || book_date[0] - year === 0) &&
(book_date[1] == "*" || book_date[1] - month === 0) &&
(book_date[2] == "*" || book_date[2] - date === 0)
) {
return false;
}
}
return true;
}
I get this issues: Cannot read property 'split' of undefined in this line
var book_date = this.unavailable[i].startDate.split("-");
please any help thanks for you
this.unavailable[i].startDate is undefined. Does listDate reference this.unavailable or is it a different array? Put a breakpoint or use console.log to inspect the contents of this.unavailable in the isAvailable function.
The code does not give me any error in my console. Can you try storing the value of unavailable in a separate variable and use that variable instead. This might help.
isAvailable: function(date, month, year) {
var unavailable = this.unavailable;
for (var i in unavailable) {
var book_date = unavailable[i].startDate.split("-");
if (book_date.length !== 3) {
return false;
} else if (
(book_date[0] == "*" || book_date[0] - year === 0) &&
(book_date[1] == "*" || book_date[1] - month === 0) &&
(book_date[2] == "*" || book_date[2] - date === 0)
) {
return false;
}
}
return true;
}
You are using a for in loop to iterate through an array - for in loops should only be used on objects. You should use a plain for loop or forEach
isAvailable: function(date, month, year) {
for (var i = 0; i < this.unavailable.length; i++) {
var book_date = this.unavailable[i].startDate.split("-");
if (book_date.length !== 3) {
return false;
} else if (
(book_date[0] == "*" || book_date[0] - year === 0) &&
(book_date[1] == "*" || book_date[1] - month === 0) &&
(book_date[2] == "*" || book_date[2] - date === 0)
) {
return false;
}
}
return true;
}

Javascript String Manipulation and Conversion with Range

I have a string like this (must be in this format):
var string = "[0] No new notifications | [1,] Some new notifications"
And I want to get "No new notifications" if a variable is 0 and if that variable is 1 or greater, show "Some new notifications".
How can I do that?
Here's a generic processesor for ISO 31-11 strings. It takes the ISO 31-11 string and the numeric value, then returns the appropriate string or undefined. Here's a fiddle.
function processISO31_11(rangeGuide, n) {
var separator = /\[(\d+)(,)?(\d+)?\]\s?(.+)/;
var rangeGuides = rangeGuide.split('|');
var guideCount = rangeGuides.length;
for (var guide = 0; guide < guideCount; guide++) {
var elements = separator.exec(rangeGuides[guide]);
if (elements != null) {
if (n < parseFloat(elements[1])) {
return; // return undefined indicating failure to match any range
}
if (n == parseFloat(elements[1])) {
return elements[4];
}
if (elements[2] === "," && (typeof elements[3] === "undefined" || n <= parseFloat(elements[3]))) {
return elements[4];
}
}
}
}
var somevar = 3;
var yourString = '[0] No new notifications | [1,] Some new notifications';
var notification = yourString .split(' | ');
var message=(somevar == 0 ? notification[0].split('] ')[1] : notification[1].split('] ')[1]);
the var message has your needed output.
After examining more closely exactly what you are looking for, I have come up with a solution that will read in the rules you pass it and essentially turn that into logic that your program will follow. Here is a demo of how it would work:
var myVar = 3;
var myStr = '[0] No new notifications | [1,4] Some new notifications | [5,] Several new notifications';
var notificationRules = getRules(myStr);
function getRules(rulesString) {
return rulesString.split(' | ').map(function(rule) {
var startValue, endValue;
var values = rule.match(/\[\d*,?\d*\]/g)[0];
values = values.replace(/\[|\]/g, "").split(",");
startValue = values[0];
endValue = +values[1] === 0 ? Infinity : values[1];
return {
startValue: Number(startValue),
endValue: endValue != undefined ? Number(endValue) : undefined,
message: rule.replace(/\[\d*,?\d*\]/g, "").trim()
};
});
}
function getMessage(myVar, rules) {
var message = "No rule match!";
rules.some(function(rule) {
if (myVar === rule.startValue) {
message = rule.message;
return true;
} else if (myVar >= rule.startValue && myVar <= rule.endValue) {
message = rule.message;
}
});
return message;
}
console.log(getMessage(0, notificationRules));
console.log(getMessage(2, notificationRules));
console.log(getMessage(5, notificationRules));
console.log(getMessage(100, notificationRules));
console.log(getMessage(-1, notificationRules));
Complex solution using String.prototype.split(), String.prototype.match() and String.prototype.slice() functions:
var configStr = '[0] No new notifications | [1,] Some new notifications',
getNotifyMessage = function (config, num) {
var num = Number(num),
items = config.split('|'),
len = items.length, parts;
while (len--) {
parts = items[len].match(/\[(\d+,?)\]\s([\w ]+)(?=\||$)/i);
if (Number(parts[1]) === num) {
return parts[2];
}
if (parts[1].slice(-1) === ',' && Number(parts[1].slice(0,-1)) <= num) {
return parts[2];
}
}
return '';
};
console.log(getNotifyMessage(configStr, 1));
console.log(getNotifyMessage(configStr, 0));
console.log(getNotifyMessage(configStr, 3));

Javascript: how to validate dates in format MM-DD-YYYY?

I saw a potential answer here but that was for YYYY-MM-DD: JavaScript date validation
I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:
String.prototype.isValidDate = function()
{
var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
var matches = IsoDateRe.exec(this);
if (!matches) return false;
var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
return ((composedDate.getMonth() == (matches[1] - 1)) &&
(composedDate.getDate() == matches[2]) &&
(composedDate.getFullYear() == matches[3]));
}
How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?
Thanks.
function isValidDate(date)
{
var matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));
It works. (Tested with Firebug, hence the console.log().)
function isValidDate(date) {
var valid = true;
date = date.replace('/-/g', '');
var month = parseInt(date.substring(0, 2),10);
var day = parseInt(date.substring(2, 4),10);
var year = parseInt(date.substring(4, 8),10);
if(isNaN(month) || isNaN(day) || isNaN(year)) return false;
if((month < 1) || (month > 12)) valid = false;
else if((day < 1) || (day > 31)) valid = false;
else if(((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30)) valid = false;
else if((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29)) valid = false;
else if((month == 2) && ((year % 100) == 0) && (day > 29)) valid = false;
else if((month == 2) && (day > 28)) valid = false;
return valid;
}
This checks for valid days in each month and for valid leap year days.
How about validating dates in "ANY" date format? I've been using the DateJS library and adding it to existing forms to ensure that I get valid dates & times formatted the way that I want. The user can even enter things like "now" and "tomorrow" and it will be converted into a valid date.
Here's the dateJS library:
http://www.datejs.com/
and here's a jQuery tip that I wrote:
http://www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm
I would use Moment.js for this task. It makes it very easy to parse dates and it also provides support to detect a an invalid date1 in the correct format. For instance, consider this example:
var formats = ['MM-DD-YYYY', 'MM/DD/YYYY']
moment('11/28/1981', formats).isValid() // true
moment('2-29-2003', formats).isValid() // false (not leap year)
moment('2-29-2004', formats).isValid() // true (leap year)
First moment(.., formats) is used to parse the input according to the localized format supplied. Then the isValid function is called on the resulting moment object so that we can actually tell if it is a valid date.
This can be used to trivially derive the isValidDate method:
String.prototype.isValidDate = function() {
var formats = ['MM-DD-YYYY', 'MM/DD/YYYY'];
return moment("" + this, formats).isValid();
}
1 As I can find scarce little commentary on the matter, I would only use moment.js for dates covered by the Gregorian calendar. There may be plugins for other (including historical or scientific) calendars.
I use this regex for validating MM-DD-YYYY:
function isValidDate(subject){
if (subject.match(/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/)){
return true;
}else{
return false;
}
}
It will match only valid months and you can use / - or . as separators.
This function will validate the date to see if it's correct or if it's in the proper format of: DD/MM/YYYY.
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[1];
var m = matches[2]-1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));
what isn't working about it? here's a tested version:
String.prototype.isValidDate = function() {
const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
if (!match || match.length !== 4) {
return false
}
const test = new Date(match[3], match[1] - 1, match[2]);
return (
(test.getMonth() == match[1] - 1) &&
(test.getDate() == match[2]) &&
(test.getFullYear() == match[3])
);
}
var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true
You can simplify it somewhat by changing the first two lines of the function to this:
var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
Or, just change the parameter to the RegExp constructor to be
^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$
Simple way to solve
var day = document.getElementById("DayTextBox").value;
var regExp = /^([1-9]|[1][012])\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;
return regExp.test(day);
pass this function to date with format //10-10-2012 and id of object.
function isValidDateFormat(date, id)
{
var todayDate = new Date();
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null)
{
if(date != '__-__-____')
{
alert('Please enter valid date');
}
}
else
{
var day = 31;
var month = 12;
var b_date = date.split("-");
if(b_date[0] <= day)
{
if(b_date[1] <= month)
{
if(b_date[2] >= 1900 && b_date[2] <= todayDate.getFullYear())
{
return true;
}
else
{
$("#"+id).val('');
alert('Please enter valid Year');
}
}
else
{
$("#"+id).val('');
alert('Please enter valid Month');
}
}
else
{
alert('Please enter valid Day');
$("#"+id).val('');
}
}
}
This is for validating the date string in formate dd.mm.yyyy It is easy to customize it. You just need to adjust the pos1 and pos2 in isValidDate().
var dtCh= ".";
var minYear=1900;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31;
if (i==4 || i==6 || i==9 || i==11) {
this[i] = 30;
}
if (i==2) {
this[i] = 29;
}
}
return this;
}
function isValidDate(dtStr){
var daysInMonth = DaysArray(12);
var pos1=dtStr.indexOf(dtCh);
var pos2=dtStr.indexOf(dtCh,pos1+1);
var strDay=dtStr.substring(0,pos1);
var strMonth=dtStr.substring(pos1+1,pos2);
var strYear=dtStr.substring(pos2+1);
strYr=strYear;
if (strDay.charAt(0)=="0" && strDay.length>1)
strDay=strDay.substring(1);
if (strMonth.charAt(0)=="0" && strMonth.length>1)
strMonth=strMonth.substring(1);
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1)
strYr=strYr.substring(1);
}
month=parseInt(strMonth);
day=parseInt(strDay);
year=parseInt(strYr);
if (pos1==-1 || pos2==-1){
alert("The date format should be : dd.mm.yyyy");
return false;
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month");
return false;
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day");
return false;
}
if (strYear.length != 4 || year==0 || year<minYear){
alert("Please enter a valid 4 digit year after "+minYear);
return false;
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
alert("Please enter a valid date");
return false;
}
return true;
}
if (document.getElementById('expiryDay').value != test(match("/^([0-9]{2})\/([0-9]{2})$/"))){
alert("Enter the date in two digit month flowed by two digits year \n");
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function dateCheck(inputText) {
debugger;
var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var flag = 1;
if (inputText.value.match(dateFormat)) {
document.myForm.dateInput.focus();
var inputFormat1 = inputText.value.split('/');
var inputFormat2 = inputText.value.split('-');
linputFormat1 = inputFormat1.length;
linputFormat2 = inputFormat2.length;
if (linputFormat1 > 1) {
var pdate = inputText.value.split('/');
}
else if (linputFormat2 > 1) {
var pdate = inputText.value.split('-');
}
var date = parseInt(pdate[0]);
var month = parseInt(pdate[1]);
var year = parseInt(pdate[2]);
var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month == 1 || month > 2) {
if (date > ListofDays[month - 1]) {
alert("Invalid date format!");
return false;
}
}
if (month == 2) {
var leapYear = false;
if ((!(year % 4) && year % 100) || !(year % 400)) {
leapYear = true;
}
if ((leapYear == false) && (date >= 29)) {
alert("Invalid date format!");
return false;
}
if ((leapYear == true) && (date > 29)) {
alert("Invalid date format!");
return false;
}
}
if (flag == 1) {
alert("Valid Date");
}
}
else {
alert("Invalid date format!");
document.myForm.dateInput.focus();
return false;
}
}
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '48') && (charCode <= '57')) || (charCode == '47')) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<div>
<form name="myForm" action="#">
<table>
<tr>
<td>Enter Date</td>
<td><input type="text" onkeypress="return restrictCharacters(event);" name="dateInput"/></td>
<td></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<td></td>
<td><input type="button" name="submit" value="Submit" onclick="dateCheck(document.myForm.dateInput)" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy.
Note supplied date format and date string go hand in hand.
<script type="text/javascript">
function validate(format) {
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
Below is the HTML snippet
<input type="text" name="start" id="start" size="10" value="05/31/2016" />
<br/>
<input type="text" name="end" id="end" size="10" value="04/28/2016" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />
If your date needs to match DD.MM.YYYY and use AngularJS, use the following code:
$scope.validDate = function(value){
var matches = /^(\d{1,2})[.](\d{1,2})[.](\d{4})$/.exec(value);
if (matches == null) return false;
var d = matches[1];
var m = matches[2] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
};
console.log($scope.validDate('22.04.2001'));
console.log($scope.validDate('03.10.2001'));
console.log($scope.validDate('30.02.2001'));
console.log($scope.validDate('23.09.2016'));
console.log($scope.validDate('29.02.2016'));
console.log($scope.validDate('31.02.2016'));
More about the scope object can be found here. Without AngularJS, simply change the first line to:
ValidDate = new function(value) {
And call it using:
var MyDate= ValidDate('29.09.2016');
DateFormat = DD.MM.YYYY or D.M.YYYY
function dateValidate(val){
var dateStr = val.split('.');
var date = new Date(dateStr[2], dateStr[1]-1, dateStr[0]);
if(date.getDate() == dateStr[0] && date.getMonth()+1 == dateStr[1] && date.getFullYear() == dateStr[2])
{ return date; }
else{ return 'NotValid';}
}
try this:
function validateDate(dates){
re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
if(regs = dates.match(re)) {
// day value between 1 and 31
if(regs[1] < 1 || regs[1] > 31) {
return false;
}
// month value between 1 and 12
if(regs[2] < 1 || regs[2] > 12) {
return false;
}
var maxday=days[regs[2]-1];
if(regs[2]==2){
if(regs[3]%4==0){
maxday=maxday+1;
}
}
if(regs[1]>maxday){
return false;
}
return true;
}else{
return false;
}
}
German Variant, but could be adapted to Iso
export function isLeapYear(year) {
return (
year % 4 === 0 && (year % 100 != 0 || year % 1000 === 0 || year % 400 === 0)
)
}
export function isValidGermanDate(germanDate) {
if (
!germanDate ||
germanDate.length < 5 ||
germanDate.split('.').length < 3
) {
return false
}
const day = parseInt(germanDate.split('.')[0])
const month = parseInt(germanDate.split('.')[1])
const year = parseInt(germanDate.split('.')[2])
if (isNaN(month) || isNaN(day) || isNaN(year)) {
return false
}
if (month < 1 || month > 12) {
return false
}
if (day < 1 || day > 31) {
return false
}
if ((month === 4 || month === 6 || month === 9 || month === 11) && day > 30) {
return false
}
if (isLeapYear(year)) {
if (month === 2 && day > 29) {
return false
}
} else {
if (month === 2 && day > 28) {
return false
}
}
return true
}
Short and fast.
function dateValid(date) {
var match = date.match(/^(\d\d)-(\d\d)-(\d{4})$/) || [];
var m = (match[1] | 0) - 1;
var d = match[2] | 0;
var y = match[3] | 0;
return !(
m < 0 || // Before January
m > 11 || // After December
d < 1 || // Before the 1st of the month
d - 30 > (2773 >> m & 1) || // After the 30th or 31st of the month using bitmap
m == 1 && d - 28 > // After the 28th or 29th of February depending on leap year
(!(y % 4) && y % 100 || !(y % 400)));
}
console.log('02-29-2000', dateValid('02-29-2000'));
console.log('02-29-2001', dateValid('02-29-2001'));
console.log('12-31-1970', dateValid('12-31-1970'));
console.log('Hello', dateValid('Hello'));
Expanding on "Short and Fast" above by #Adam Leggett, as cases like "02/30/2020" return true when it should be false. I really dig the bitmap though...
For a MM/DD/YYYY date format validation:
const dateValid = (date) => {
const isLeapYear = (yearNum) => {
return ((yearNum % 100 === 0) ? (yearNum % 400 === 0) : (yearNum % 4 === 0))?
1:
0;
}
const match = date.match(/^(\d\d)\/(\d\d)\/(\d{4})$/) || [];
const month = (match[1] | 0) - 1;
const day = match[2] | 0;
const year = match[3] | 0;
const dateEval=!( month < 0 || // Before January
month > 11 || // After December
day < 1 || // Before the 1st of the month
day - 30 > (2773 >> month & 1) ||
month === 1 && day - 28 > isLeapYear(year)
// Day is 28 or 29, month is 02, year is leap year ==> true
);
return `\nDate: ${date}\n\n
Valid Date?: ${dateEval}\n
=======================================`
}
console.log(dateValid('02/28/2020')) // true
console.log(dateValid('02/29/2020')) // true
console.log(dateValid('02/30/2020')) // false
console.log(dateValid('01/31/2020')) // true
console.log(dateValid('01/31/2000')) // true
console.log(dateValid('04/31/2020')) // false
console.log(dateValid('04/31/2000')) // false
console.log(dateValid('04/30/2020')) // true
console.log(dateValid('01/32/2020')) // false
console.log(dateValid('02/28/2021')) // true
console.log(dateValid('02/29/2021')) // false
console.log(dateValid('02/30/2021')) // false
console.log(dateValid('02/28/2000')) // true
console.log(dateValid('02/29/2000')) // true
console.log(dateValid('02/30/2000')) // false
console.log(dateValid('02/28/2001')) // true
console.log(dateValid('02/29/2001')) // false
console.log(dateValid('02/30/2001')) // false
For a MM-DD-YYYY date format validation: Replace \/ in the pattern for match by -.
<script language = "Javascript">
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strDay=dtStr.substring(0,pos1)
var strMonth=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : dd/mm/yyyy")
return false
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month")
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day")
return false
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
return false
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
alert("Please enter a valid date")
return false
}
return true
}
function ValidateForm(){
var dt=document.frmSample.txtDateenter code here
if (isDate(dt.value)==false){
dt.focus()
return false
}
return true
}
</script>

Categories

Resources