HTML5 Date Validation - javascript

I'm looking to implement validation for a mobile site, where I have two input fields and I would like the first to validate the value is no later than todays date, and the second to validate it is no later than a one year in advance of the first value.
E.g
First Value = 26/11/2013
Second Value can not contain a value later than 26/11/2014
Is this possible?

I like moment.js. It makes it easier to deal with dates and times.
First, let's make sure a day "is before tomorrow". This will depend a bit upon what the definition of tomorrow is.
var m = moment("26/11/2013", "MM/DD/YYYY");
// tomorrow this time
var t = moment().add("days", 1);
// tomorrow start of day
var tomorrow = moment([t.year(), t.month(), t.date()]);
if (m.lessThan(tomorrow)) {
// today!!! (or before)
}
Similarly, the same approach can be used for a year from now. It's likely fine enough to not care about the time component in this case, and I've slogged on another day - but if it matters (e.g. looking for the start of the day), see the previous example.
var m = moment("26/11/2013", "MM/DD/YYYY");
var aYearFromNow = moment().add("years", 1).add("days", 1);
if (m.lessThan(aYearFromNow)) {
// still less than a year!
}

1) cache the elements.
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
2) The value of d1 and d2 are string data type. So split them and parse it to date format as below
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
Here the year is incremented by 1, based on the value in d1.
4) Again parse it back to string format (YYYY-MM-DD)
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
5) Set this as value for max attribute for d2
d2.setAttribute("max", maxi);
Finally add the below method to onblur event of d1.
function setMaxDate() {
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
d2.setAttribute("max", maxi);
}
JSFiddle

Better with javascript. You can I use HTML5 attribute type="date" but keep in mind it's barely supported.

You can use a Regex pattern like this /([0-9]{2})/([0-9]{2})/([0-9]{4})/, that is, two decimal digits, a slash, two more decimal digits, a slash and four decimal digits, everything grouped separately (group 1 = day, group 2 = month, group 3 = year). You would test for this pattern in a event, (I would suggest onchange, since you mentioned mobile) and also check if the numbers are within a valid range (e.g. day < 32, month < 13, year < currentYear-1).

Related

Have Javascript recognize YYYYmmdd in +5:00 Time Zone [duplicate]

I need my date to be in ccyymmdd format to add a day and pass over to a cobol application via xml. I also need to convert the new date with the added day to mm/dd/ccyy format to place into my slickgrid. My boss believes there has to be an easier way however, I can't seem to find one without using jquery or adding another library. Here is the code I am using;
// Roll date for status R1(rolled) today plus 1 day.
var rDate = (new Date()).toISOString().slice(0, 10).replace(/-/g, "");
(rDate++);
// Convert rDate back to useable date for updating ActionDate when rolling clt.
var uDate = (String(rDate)).replace(/(\d{4})(\d{2})(\d+)/, "$2/$3/$1");
So to preserve what you are doing (adding a day to the date), one solution is:
var rDate = new Date();
rDate.setDate(rDate.getDate() + 1);
var printDate = rDate.getFullYear()+('0'+(rDate.getMonth()+1)).slice(-2)+('0'+(rDate.getDate())).slice(-2);
The advantage here is that rDate is always a real Date object, so you don't have to convert it back - you can just use it for any output format you wish.
The Date object in JavaScript has getFullYear, getMonth, and day methods, which means you can do:
If you had a function pad(num, digits) which pads a number with leading zeroes, you can have:
var str = pad(date.getFullYear(), 4) + pad(1+ date.getMonth(), 2) + pad(date.getDate(), 2)
From Pad a number with leading zeros in JavaScript on stackoverflow, you can get a pad functio:
function pad(n, width) {
n += '';
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}
I don't think it's better, but another approach:
var d = new Date();
var datestr = [ d.getFullYear(), ('0' + (1+d.getMonth())).substr(-2), ("0" + d.getDate()).substr(-2) ].join('');
Two thing to clarify: getMonth() returns 0-based month number, hence the need to add 1. And the ("0" + number).substr(-2) is used to add leading zeroes to single digit numbers, because substr(-2) returns two last characters of a string.

Looking to add 1 month to current date inside a div

i am looking to display the date plus 1 month inside a div which will be used to display next invoice date. i have seen a few examples in various places, but could not implement. I also saw that there were many solutions, and some controversy surrounding each one.
Once you have a date object, just call setMonth(), passing in the current number of months plus 1.
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
You can either use this : http://jsfiddle.net/dfA8b/ if you need same date of the next month
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text(invoiceDt.toDateString());
Or
You can use this : http://jsfiddle.net/hjSDu/ if you need 30 days month(mostly used for invoice purposes)
var invoiceDt = new Date();
var days = 30;
invoiceDt.setDate(invoiceDt.getDate()+days);
$('#invoiceDate').text(invoiceDt.toDateString());
For the formatting purpose :
http://jsfiddle.net/7bU6n/
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text((invoiceDt.getMonth()+1) +"-"+ invoiceDt.getDate() +"-" + invoiceDt.getFullYear());
also see : https://stackoverflow.com/a/1643468/3603806
1 month is not so clear... what You mean? 31, 30 days or if exists simply same date of the following month?
1st case: (assuming 31 days)
var d = new Date(),
dplus31 = d.getDate() + 31;
d.setDate(dplus31);
console.debug(d, dplus31);
2nd case: one month
var d = new Date(),
dplus1 = d.getMonth() + 1;
d.setMonth(dplus1);
console.debug(d, dplus1);
..but even in this case there are some edge cases (ex. 31 January)
hope it helps
function addMonthsNoOverflow(dateParam, intParam) {
var sum = new Date(new Date(dateParam.getTime()).setMonth(dateParam.getMonth() + intParam);
if (sum.getDate() < dateParam.getDate()) { sum.setDate(0); }
return(sum);
}
Notes:
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

Customize javascript Date

I have a simple code that echos the current Hour+Minute+Date as one number sequence.
I need to add 1 to all the numbers outputted, individually.
Example: If the current time and date is: 22321512 then i need jQuery to output: 33432623.
My knowledge in jQuery is pretty slim, How can this be achieved?
HTML:
<span id="date"></span>
Code:
var now = dateFormat(new Date(), "HHMMddmm");
$('#date').append(now);
You need to do the following roughly:
var currentDate = new Date();
var myDate = new Date(currentDate.getYear() + 1, currentDate.getMonth() + 1, currentDate.getDay() + 1);
alert(myDate.getTime());
Should solve your problem.
If you want to merely increment each unit by 1 and let the JavaScript engine advance the date and time on overflow, then Captain John's answer will work perfectly.
This means that, for example, if this routine were to be run at 11:59 PM on December 31, your output would be 00000100.
If you want each unit to be incremented by 1 without the date being advanced, you will have to stop relying on Steven Levithan's [excellent] dateFormat library and do it yourself:
var now = new Date(),
hours = now.getHours() + 1, // add 1 hour
minutes = now.getMinutes() + 1, // add 1 minute
date = now.getDate() + 1, // add 1 day
month = now.getMonth() + 1, // add 1 month
padLeft = function (val) { // make a formatter
while (val.length < 2) {
val = '0' + val; // string is less than 2 characters, pad left side with '0'
}
return val; // return formatted string
},
formatted = padLeft(hours) + padLeft(minutes) + padLeft(date) + padLeft(month);
$('#date').append(formatted);
Getting number length as string you can easily sum 1 to each number.
The result is given as timestamp
To get Date object, use new Date(result);
var now = new Date().getTime(); // 22321512 on your example
// Answer
var result = 0;
var str = now.toString();
for(var i = 0; i < str.length; i++) {
result += Math.pow(10, i);
}
result += now; // Ex.: 22321512 + 11111111

How to add weeks to date using javascript?

Javascript definitely isn't my strongest point. I've been attempting this for a couple of hours now and seem to be getting stuck with date formatting somewhere.
I have a form where a user selected a date (dd/mm/yyyy) and then this date will be taken and 2 weeks will be added to it and then date will be copied to another form field.
My latest attempt below isn't even adding a date yet just copying the selected date in one form field to another, if I select '03/02/2012', it outputs 'Fri Mar 02 2012 00:00:00 GMT+0000 (GMT Standard Time)', so its outputting in American format as well as the full date. How to I get it to out put in the same format and add 2 weeks?
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
document.frmAccept.acceptLicence.value = date1;
}
You can do this :
const numWeeks = 2;
const now = new Date();
now.setDate(now.getDate() + numWeeks * 7);
or as a function
const addWeeksToDate = (dateObj,numberOfWeeks) => {
dateObj.setDate(dateObj.getDate()+ numberOfWeeks * 7);
return dateObj;
}
const numberOfWeeks = 2
console.log(addWeeksToDate(new Date(), 2).toISOString());
You can see the fiddle here.
According to the documentation in MDN
The setDate() method sets the day of the Date object relative to the beginning of the currently set month.
This might not answer the question per se, but one can find a solution with these formulas.
6.048e+8 = 1 week in milliseconds
Date.now() = Now in milliseconds
Date.now() + 6.048e+8 = 1 week from today
Date.now() + (6.048e+8 * 2) = 2 weeks from today
new Date( Date.now() + (6.048e+8 * 2) ) = Date Object for 2 weeks from today
You're assigning date1 to be a Date object which represents the string you pass it. What you're seeing in the acceptLicense value is the toString() representation of the date object (try alert(date1.toString()) to see this).
To output as you want, you'll have to use string concatenation and the various Date methods.
var formattedDate = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
In terms of adding 2 weeks, you should add 14 days to the current date;
date1.setDate(date.getDate() + 14);
... this will automatically handle the month increase etc.
In the end, you'll end up with;
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
N.B Months in JavaScript are 0-indexed (Jan = 0, Dec = 11), hence the +1 on the month.
Edit: To address your comment, you should construct date as follows instead, as the Date argument is supposed to be "A string representing an RFC2822 or ISO 8601 date." (see here).
var segments = acceptCompletionDate.split("/");
var date1 = new Date(segments[2], segments[1], segments[0]);
This should do what you're looking for.
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
}
To parse the specific dd/mm/yyyy format and increment days with 14 , you can do something like split the parts, and create the date object with y/m/d given specfically. (incrementing the days right away) Providing the separator is always -, the following should work:
function LicenceToOccupy(acceptCompletionDate)
{
var parts = acceptCompletionDate.split("/");
var date1 = new Date(parts[2], (parts[1] - 1), parseInt(parts[0]) + 14); //month 0 based, day: parse to int and increment 14 (2 weeks)
document.frmAccept.acceptLicence.value = date1.toLocaleDateString(); //if the d/m/y format is the local string, otherwise some cusom formatting needs to be done
}
date1.toLocaleDateString()
Thiswill return you date1 as a String in the client convention
To create a new date date2 with 2 weeks more (2weeks = 27246060 seconds):
var date2 = new Date(date1 + 60*60*24*7*2);

Is there a way to increment time using javascript?

So I am storing times as '01:30:00'. I have a start time and a date time dropdown. I want the dropdown to be set to the start time + 1hr. Is there a way to add the time via javascript or jquery?
Here's my current code:
$(".start_time").change(function(){
$(".end_time").val($(this).val());
});
Try this:
find the selected index of the start time
bump it up by 2 to find your end time index (given that you've got half hour increments)
use the mod operator % to wrap back to index 0 or 1 (for 00:00 and 00:30 respectively)
$(".start_time").change(function(){
var sel =$(this).attr('selectedIndex');
var endIdx = (sel + 2) % 48; // 47 is 23:30, so 48 should go back to index 0
$(".end_time").attr('selectedIndex', endIdx);
});
Try it out on JSBin.
There are two separate problems here: the first is parsing out the time from your .start_time input, and the second is incrementing it to be an hour later.
The first is really a string-manipulation exercise. Once you have parsed out the pieces of the string, e.g. via a regex, you could either turn them into a Date instance and use setHours, or you could just manipulate the components as numbers and them reassemble them into a string in the format you desire.
An example of this might be as follows:
var TIME_PARSING_REGEX = /([0-9]{2}):([0-9]{2}):([0-9]{2})/;
function padToTwoDigits(number) {
return (number < 10 ? "0" : "") + number;
}
$(".start_time").change(function () {
var stringTime = $(this).val();
var regexResults = TIME_PARSING_REGEX.exec(stringTime);
var hours = parseInt(regexResults[1], 10);
var newHours = (hours + 1) % 24;
var newHoursString = padToTwoDigits(newHours);
var minutesString = regexResults[2];
var secondsString = regexResults[3];
var newTimeString = newHoursString + ":" + minutesString + ":" + secondsString;
$(".end_time").val(newTimeString);
});
Basic example...
var date = new Date();
var h = date.getHours() + 1;
var m = date.getMinutes();
var s = date.getSeconds();
alert('One hour from now: ' + h + ':' + m + ':' + s);
Demo: http://jsfiddle.net/fBaDM/2/
After you parse you date/time string, you can use methods such as .setHours in your date object (more info at Mozilla Developer Center).
I highly recommend the DateJS library for working with date and time. I'm sure it'll be very handy for you.
protip: try to avoid replacing JavaScript with "jQuery markup"; it's all JS, after all. :)

Categories

Resources