Validating date in javascript with format d, MMM yyyy - javascript

How can i validate a date input by the user to make sure that the date entered is within the accepted limit
(e.g. date does not exceed 29 for feb, 30 for apr, jun, and nov and 31 for jan, mar, may, jul, aug, oct and dec) and the months not exceeding 12?
I have tried to add in conditions and the && simply does not work for me as it always returns an error.
My javascript function is as below:
function parseDate(s)
{
var dP = s.split("/");
var date = new Date(dP[2], (dP[1] - 1), dP[0]);
var dateStrParts = date.toString().split(" ");
return (date.getDate() + ", " + dateStrParts[1] + " " + dateStrParts[3]);
}
I have an onchange currently that will convert the month number to month name from user input and i believe i need to add another function for validation.
Hence how could i write the validation function and how should i add it into my onchange event?
There is no submit button for the date.
Thanks!

Use isNaN to check Date.parse()
function parseMyDate(s){
if (isNaN(Date.parse(s))){
alert("Your input has no logic at all");
return;
}
var dateParts = s.split("/");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
var dateStrParts = date.toString().split(" ");
return (date.getDate() + ", " + dateStrParts[1] + " " + dateStrParts[3]);
}
console.log(parseMyDate("31/02/2014"));
EDIT JSFiddle Demo

Related

Google sheet / javascript not evaluating dates as expected

I have a PHP script that records a timestamp in a Google Sheet. When I tried to see if this timestamp is between two other timestamps that I have entered manually into the same sheet, I discovered some odd behavior. I thought it might be because Google added a ' at the start of the string in the cell so I tried doing a substr to remove the apostrophe.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault;
}
Output is:
dateFromPhp: 16/01/2020 08:33:45
dateSubStr: Mon Jun 01 2020 08:33:45 GMT+1000 (AEST)
dateDefault: Thu Apr 01 2021 08:33:45 GMT+1100 (AEDT)
I have no idea why these dates are months or years away from the expected and with different timezones. The operation without the substr resulted in the correct timezone for me.
Any idea how I can make this string into a timestamp with the correct date?
I discovered the answer. I had no idea javascript expected mm/dd/yyyy as the order for the date format.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
var dateUs = americanizeDate(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault + " dateUS: " + dateUs;
}
function americanizeDate(ausDate) {
var dateParts = ausDate.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var usDate = new Date(dateParts[1]+"/"+dateParts[0]+"/"+ dateParts[2]);
return usDate;
}
Switching the month and the day solved the problem.

copy a date object from a user entered date

I am trying to put together a mostly automated form. I have the get current date fine but I am having problems collecting information from a user enter date to place it in another part of the form as well + 1 year. I.E. D.O.B = 08/06/2016 farther down the form expires 08/06/2017. I can make the current date enter automatically but when i try and get the date entered from the user nothing fills the lower date. I tried getting the date using document.getElementById('dob')
function datePone()
{
var date = new Date();
var day = date.getDate(document.getElementById('dob'))
var month = date.getMonth(document.getElementById('dob')) + 1;
var year = date.getFullYear(document.getElementById('dob')) + 1;
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var oneYear = year + "-" + month + "-" + day;
document.getElementById("dateOneYear").value = oneYear;
}
I've tried using set date or making a new var using document.getElementById('dob') but nothing i have tried has worked so far.
Since "dob" is an input field, to the get the entered data you need to use value property, so try
document.getElementById('dob').value
Also I suggest using momentjs library to manipulate with dates.
Where you have:
var day = date.getDate(document.getElementById('dob'))
the getDate method does not take any arguments, so they are ignored and the above is equivalent to:
var day = date.getDate()
You don't specify what format you're using for the string, "08/06/2016" is ambiguous. Does it represent 8 June or August 6?
You should not use the Date constructor or Date.parse to parse date strings, write your own small function or use a library. Also, adding one year to a date like 29 Feb 2016 will end up on 1 March 2017, so you need to apply a rule to accept that or change it to 28 Feb 2017.
Anyhow, assuming the input is in the format dd/mm/yyyy and you want the output date in the format yyyy-mm-dd, you can use a library or small functions like the following:
// Parse string in d/m/y format
// If invalid, return invalid Date
function parseDMY(s){
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Return date string in yyyy-mm-dd format
function toISODate(d) {
return d.getFullYear() + '-' +
('0' + (d.getMonth()+1)).slice(-2) + '-' +
('0' + d.getDate()).slice(-2);
}
// Parse string to Date
var d = parseDMY('06/08/2016');
// Add one year
d.setFullYear(d.getFullYear() + 1);
console.log(toISODate(d));
Using a library like fecha.js, you'd parse the string using:
var d = fecha.parse('06/08/2016','DD/MM/YYYY');
and format the output:
fecha.format(d, 'YYYY-MM-DD')

Convert string to date and compare two dates in javascript

I get a date in a variable in string format in javascript. It is like 26-02-2015.
Then I get today's date in another variable using new Date(). This gives me a long string like Mon Feb 23 2015 10:56:23 GMT+0530 (India Standard Time)
How can I compare these two date? I want to check which date is bigger.
This is what I am doing
var date = objParam[0].value;
var todaysDate = new Date();
if (date > todaysDate)
alert("Please select the valid date");
Use it like this:
date = new Date();
dateNew = (date.getDate()).toString() + "-" +
(date.getMonth() + 1).toString() + "-" +
(date.getFullYear()).toString();
dateNew contains the string with the format you mentioned. Now you can compare the two strings.
var d1='26-02-2015';
d1=d1.split('-');
var parsedDate=d1[1]+'/'+d1[0]+'/'+d1[2];
if(Date.now() > new Date(parsedDate).getTime()){
alert('past date')
} else {
alert('future date');
}

Change the date format my identifying the date and month?

function date()
{
var myDate=new Date(document.getElementById('date').value); //get the date from a textfield
var day=myDate.getDate();
var month=myDate.getMonth()+1;
var yr=myDate.getFullYear();
if(dateformat=="dd/mm/yyyy") //checking the date format //
{
document.getElementById('date').value=day + "/" + month + "/" + yr;
}
else
{
document.getElementById('date').value=month+"/"+day + "/" +yr;
}
}
This function onchange is written in onchange mehod of textbox date,on changing the textfield it should change the date format that is set by default.
If dd/mm/yyy is the format then change it in that format and if mm/dd/yyy then change in this format.My code does the changes, but it cannot recognize which is the month!
For example.. if the date format is mm/dd/yyy and I type the date as 11/01/2001' (NOV -1 2001) it changes to01/11/2011` which should not be done.
But if I type 01-11-2001 (jan 1 2001) which is entered is correct ,but it changes to 11/01/2001
How can I change the code to correct this??? plz help!!!
Demo Fiddle
Javascript Code
function dateChange() {
var e = document.getElementById("dateformat");
var dateformat = e.options[e.selectedIndex].text;
var myDate;
if (dateformat == "dd/mm/yyyy") //checking the date format //
{
var value = document.getElementById('date').value;
var format = value.split("/");
myDate = new Date(format[2], format[1] - 1, format[0]);
var day = myDate.getDate();
var month = myDate.getMonth() + 1;
var yr = myDate.getFullYear();
document.getElementById('date').value = day + "/" + month + "/" + yr;
} else {
myDate = new Date(document.getElementById('date').value);
var day = myDate.getDate();
var month = myDate.getMonth() + 1;
var yr = myDate.getFullYear();
document.getElementById('date').value = month + "/" + day + "/" + yr;
}
document.getElementById('dateStr').innerHTML = myDate.toDateString();
}
Enter the date 01/02/2014 with mm/dd/yyyy in drop down the date would be Thu Jan 02 2014, now just change the drop down to dd/mm/yyyy the date would be Sat Feb 01 2014
Instantiating Javascript's Date object require this format new Date(yyyy,mm,dd), so when you use dd/mm/yyyy you need to manually ex-change the dd & mm values...
Reference
I guess the problem is that you either don't have dateformat specified or you compare it wrong.
if(dateformat=="dd/mm/yyyy")
If that always returns false, you will always get the second option.
Make sure dateformat is visible in the date() function, and make sure it actually gets the value you want it to have.
Secondly - the new Date() function actually parses the date before you check for the date format. I think you might want to do it the other way around: parse the input date, check which format it is in, and then output the result.

Add days to date using Javascript

I am trying to add days to a given date using Javascript. I have the following code:
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var joindate = new Date(datepicker);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
On first alert I get the date 24/06/2011 but on second alert I get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong I want it to remain 24/06/2011 so that I can add days to it. In my code I want my final output to be 25/06/2011.
Fiddle is # http://jsfiddle.net/tassadaque/rEe4v/
Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:
var dmy = "24/06/2011".split("/"); // "24/06/2011" should be pulled from $("#DatePicker").val() instead
var joindate = new Date(
parseInt(dmy[2], 10),
parseInt(dmy[1], 10) - 1,
parseInt(dmy[0], 10)
);
alert(joindate); // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time)
joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
alert(joindate); // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
alert(
("0" + joindate.getDate()).slice(-2) + "/" +
("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
joindate.getFullYear()
);
Demo here
I would like to encourage you to use DateJS library. It is really awesome!
function onChange(e) {
var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
var new_date = date.add(n).days();
$('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}
Assuming numberOfDaysToAdd is a number:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
The first alert is the value of the field. the second is the generated date from a non-US formatted date.
Here is a working example (seems that this kind of markup is necessary to get noticed)
If you want to keep your code, then you need to change
var joindate = new Date(datepicker);
to
var parms = datepicker.split("/");
then use
var joindate = new Date(parms[1]+"/"+parms[0]+"/"+parms[2]);
OR the identically working
var joindate = new Date(parms[2],parms[1]-1,parms[0]);
As pointed out in a few other answers too, use the .getDate()
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
Lastly you want to add a 0 if the month is < 10
if (mm<10) mm="0"+mm;
If you are using the datepicker from jQuery UI, then you can do
$('.new').val($("#DatePicker").datepicker( "setDate" , +1 ).val());
instead of your function
http://jqueryui.com/demos/datepicker/#method-setDate
Sets the current date for the
datepicker. The new date may be a Date
object or a string in the current date
format (e.g. '01/26/2009'), a number
of days from today (e.g. +7) or a
string of values and periods ('y' for
years, 'm' for months, 'w' for weeks,
'd' for days, e.g. '+1m +7d'), or null
to clear the selected date.
Try
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var parts = datepicker.split(/[^\d]/);
var joindate = new Date();
joindate.setFullYear(parts[2], parts[1]-1, parts[0]);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
I suppose the problem is JavaScript expects format MM/DD/YYYY not DD/MM/YYYY when passed into Date constructor.
To answer your real problem, I think your issue is that you're trying to parse the text-value of the DatePicker, when that's not in the right format for your locale.
Instead of .val(), use:
var joindate = $('#DatePicker').datepicker("getDate");
to get the underyling Date() object representing the selected date directly from jQuery.
This guarantees that the date object is correct regardless of the date format specified in the DatePicker or the current locale.
Then use:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
to move it on.
Is it a typo round joindate.setDate(joindate + numberOfDaysToAdd)?
I tried this code, it seems ok to me
var joindate = new Date(2010, 5, 24);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
alert(joinFormattedDate);
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
and in your javascript code you could call
var currentDate = new Date();
// to add 8 days to current date
currentDate.addDays(8);
function onChange(e) {
var datepicker = $("#DatePicker").val().split("/");
var joindate = new Date();
var numberOfDaysToAdd = 1;
joindate.setFullYear(parseInt(datepicker[2]), parseInt(datepicker[1])-1, parseInt(datepicker[0])+numberOfDaysToAdd);
$('.new').val(joindate);
}
http://jsfiddle.net/roberkules/k4GM5/
try this.
Date.prototype.addDay = function(numberOfDaysToAdd){
this.setTime(this.getTime() + (numberOfDaysToAdd * 86400000));
};
function onChange(e) {
var date = new Date(Date.parse($("#DatePicker").val()));
date.addDay(1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}

Categories