Javascript Date Time Validation - yyyy-mm-dd hh:mm - javascript

I want to create a very simple javascript form validation. I have two input boxes that are populated by a datetime picker. the datetime picker populates the input box with in the format 2011-12-21 09:58. I have an input box for collection date and arrival date.
I want to validate that the 'deliverdatetime' entered is greater than the 'collectdatetime'.
The output of a failed validation should just be in a popup window saying 'deliverdate' before 'coolectdate'.
Can this be done with javascript and if so can someone give me a brief example?
my basic html form code is:
...
<td>
<input type="text" id="collectdatetime" name="collectdatetime">
</td>
<td>
<input type="text" id="deliverdatetime" name="deliverdatetime" >
</td>
...
Thanks in advance for the assistance and happy holidays to everyone.
Regards,
Ryan Smith

GIven the ISO8601 format of the date/time string, you can just compare the values as strings. It's one of the beauties of using an ISO8601 format. You have asked for the delivery time to be after the collection time, which seems backwards to me but anyhow…
<form onsubmit="return checkDates(this)">
<table>
<tr>
<td>
<input type="text" id="collectdatetime" name="collectdatetime">
<td>
<input type="text" id="deliverdatetime" name="deliverdatetime">
<td>
<input type="submit">
</table>
</form>
<script>
function checkDates(form) {
if (form.collectdatetime.value >= form.deliverdatetime.value) {
alert('Collection time must be after deliver time');
return false;
}
}
</script>

You could do something like this:
var collectTime = (new Date(document.getElementById("collectdatetime").value)).getTime(),
deliverTime = (new Date(document.getElementById("deliverdatetime").value)).getTime();
if(deliverTime > collectTime) {
//Ok!
}
This creates 2 Date objects, passing the selected values to the constructor, and then compares the times. The getTime method returns a number representing the time that has passed since 1 January 1970 00:00:00 in milliseconds.
Here's a working example.

You can create Date object from this values and compare them:
var collect = new Date($('#collectdatetime').val());
var delivery = new Date($('#deliverdatetime').val());
if (delivery < collect) {
alert('Delivery date before collect!');
}

Related

Format Angular Date for DB storage

Thank you in advance
Q.1
I would like to format the Angular-UI Bootstrap date and time pickers. Every time I change the time or date the output is in the following manner Today is: "2015-03-19T22:00:00.000Z". Obviously this is in correct. And my Node-Mysql is filled with this date formatting
What's more bizzar is that There is 1 day subtracted in the date, On the time it subtracts 2 hours. My Time zone is GMT+2 See MyBin.
When I click on the date again to change it I want the date to stay as 2015-03-20 and the time to 11:20
Q.2
How can I properly validate the following
<form name="BookingForm" ng-repeat="adult in myAdults">
<h4>Adults</h4>
<p>
<input required
ng-required="true"
name="adultName"
ng-model="adultItem.name"
type="text"
class="form-control"
ng-minlength = 3
placeholder="Name">
<div class="error" ng-show="BookingForm.adultName.$dirty && BookingForm.adultName.$invalid">
<small class="error btn-danger"
ng-show="BookingForm.adultName.$error.required">
Your name is required.
</small>
<small class="error btn-danger"
ng-show="BookingForm.adultName.$error.minlength">
Your name is required to be at least 3 characters
</small>
</div>
</p>
</form>
My js Looks like this
$scope.adults = 4;
$scope.children = 2;
$scope.myAdults = [];
for (i = 0; i < $scope.adults; i ++) {
$scope.myAdults.push({});
}
If I have just one form it works fine. But if I have more than one The validation messages only show up on the last one.
Most Important is Q1
Thank you again.
datepicker is using angularjs date filter and it's localised but returned values are in GMT so 2015-03-19T22:00:00.000Z is correct for 2015-03-12T00:00:00.000Z as it will subtract 2 hours from midnight back which changes date as well, if you need a specific format you can do it with date filter as per plunker so
{{'2015-03-19T22:00:00.000Z' | date:'dd-MMMM-yyyy'}} in your timezone shall return 20-March-2015
http://angular-ui.github.io/bootstrap/#/datepicker
http://plnkr.co/edit/CoIS2BFK5O5EAaTu4Vc2?p=preview
javascript
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];

jquery filter comparing dates

I'm currently trying to create a filter that will allow me to select a date using jQueryUI datepicker. This date will then be compared to the value of a hidden input. The parent div of the hidden input will then be hidden using .hide() function if the hidden date is less than the date select using the picker.
<div data-value="I0001-APP0277-S" class="server_wrapper" style="display: block;">
<div class="detail_wrapper">....</div>
<input type="hidden" class="buildStart_hidden" value="4/25/2014 1:46:19 pm">
</div>
<input type="text" id="buildStart_filter" class="secondary_live_filter hasDatepicker">
Using this code:
$('#buildStart_filter').change(function(){
var date = $(this).val();
$('.buildStart_hidden').each(function(){
if(date>$(this).val().split(' ')[0]){
$(this).parent().hide();
}
});
});
But using this code doesn't work. I think it may be due to the comparison of string values rather than date values. What can I change to make the comparison work?
Maybe:
You missing to remove the hour from DATE
date.split(' ')[0] > $(this).val().split(' ')[0]
After some more work I have figured out the problem.
I was trying to compare string types and not Date types.
This code is working now as hiddenDate and FilterDate are Date() types and thus can be evaluated using >= operator:
$('#buildStart_filter').change(function(){
var filterDate = $('#buildStart_filter').datepicker('getDate');
$('.buildStart_hidden').each(function(){
var hiddenDateStr = $(this).val();
var hiddenDate = new Date(hiddenDateStr);
if(filterDate>=hiddenDate){
$(this).parent().hide();
}else{
$(this).parent().show();
}
});
});

How to calculate date difference in html using java script without clicking submit button

I am giving two dates manually in the form after that one more empty box is there date difference should get calculated in terms of days in third box dynamically using java script
for me its working when i am clicking submit button and using submit button property but i want it should get calculated after entering second date into second box and it should display in third box here is my code....
please help me out here..
Script
function dateDiff() {
date1 = new Date();
date2 = new Date();
diff = new Date();
date1temp = new Date(dateform.firstdate.value);
date1.setTime(date1temp.getTime());
date2temp = new Date(dateform.seconddate.value);
date2.setTime(date2temp.getTime());
diff.setTime(Math.abs(date1.getTime() - date2.getTime()));
timediff = diff.getTime();
days = Math.floor(timediff / (1000 * 60 * 60 * 24));
dateform.difference.value = days;
return false;
}
html
<form>
<fieldset>
<label for="Enter leave starting date">Enter leave starting date
<input type="text" name="firstdate" />
</label>
<label for="Enter leave ending date">Enter leave ending date
<input type="text" name="seconddate" onkeyup="return dateDiff();" />
</label>
<label>
Date Difference (in days): <input type=text name=difference>
</label>
</fieldset>
</form>
Actually, the code works...the only thing you need is to give the form the name you use in the script
<form name="dateform">
....i tested it on your fiddle, it works like a charm: http://jsfiddle.net/byJKg/5/
...tough you might want to check if the datediff is not NaN
if(!isNaN(days)){
dateform.difference.value = days;
}
[edit] ...i just saw it wasn't your fiddle....but the fiddle posted by Felix Lahmer, with your source code

Check if date in field is more than x

I would like to have a function that checks if a date in a field is more than 50 years in the past from todays date. If the date is more than 50 years in the past, a message should be shown, but there should not be any minimum date (maximum years).
I have a form where it is possible to add more fields dynamically (name + birthdate), and every new "form" should show this message under the birthday field if it is more than 50 years in the past.
The warning message under each birthdate field should be something like this (if over 50):
<div class="alert alert-warning">This person is over 50 year. Remember to do...</div>
My html setup:
<label for="id_nested-0-name">Name</label>
<input id="id_nested-0-name" maxlength="200" name="nested-0-name" type="text" />
<label for="id_nested-0-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-0-birthdate" name="nested-0-birthdate" type="date" />
<!-- If nested-0-birthdate is over 50, add html with warning message -->
<!-- New person -->
<label for="id_nested-1-name">Name</label>
<input id="id_nested-1-name" maxlength="200" name="nested-1-name" type="text" />
<label for="id_nested-1-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-1-birthdate" name="nested-1-birthdate" type="date" />
<!-- If nested-1-birthdate is over 50, add html with warning message -->
Edit:
This code works great in chrome, but does not work in safari. Anyone see what could be wrong?
<script type="text/javascript">
$(document).ready(function() {
$(function(){
$("#collapse1 input.dateinput").on("change.dp change keyup paste click propertychange",function (e){
var timediff1 = moment().diff(moment($(this).val()), 'years');
if (timediff1 >= 50 ) {
$('#alert1').remove();
$('#collapse1 .panel-body').append('<div id="alert1">Over 50!</div>');
} else {
$('#alert1').remove();
}
});
});
});
</script>
Using http://eonasdan.github.io/bootstrap-datetimepicker/ for my date picker.
Edit 2:
I was missing data-format="DD/MM/YYYY" on my input. Now everything works!
If you dont mind using moment.js
JSFiddle with demo
boolean isOldGeezer = moment().diff(moment($(this).val()), 'years') > 50;
Three part answer to this question
First you need to get the date 50 years ago. I am using a small hack here. You can find better techniques in StackOverflow.
ago50y = new Date();
ago50y.setFullYear(ago50y.getUTCFullYear()-50);
Second, compare that date when the input changes. The following code uses jQuery.
$('input.dateinput').change(function (event) {
if ($(event.target).val() < ago50y.toJSON().slice(0,10)) {
$('#alert').text('This person is over 50 year. Remember to do...');
} else {
$('#alert').text('');
}
});
Third, invoke the second part whenever you add a new set of inputs. Put the above code in a function and include that in the callback while adding the new set.
http://jsfiddle.net/FA4hJ/

date format in php is giving wrong result

I have created one form as following:
<form action="test.php" method="POST" name="edituser">
<input type="text" id="to_date_picker" placeholder="Select Date" name="todate" class="input" size="50" />
<input name="addnew" type="submit" value="Add & Save" id="submitbtn" />
</form>
<script type="text/javascript">
$(function() {
$('#to_date_picker').datepick();
});
</script>
test.php: is as following:
$todate = $_POST['todate'];
$newtodate = date("Y-m-d", strtotime($todate));
echo $newtodate."<br>\n";
here it is giving wrong output. here date picker is a calender from which date is picked.
What is your dateformat? Because the default dateformat for datepick is "mm/dd/yyyy". strtotime accept this format for date:
American month, day and year mm "/" dd "/" y "12/22/78", "1/17/2006", "1/17/6"
I think that your datepick returns 01/17/2006.
Look for this.
You can search for mktime function, then you can parse your datetime for the proper format.
use this instead
$('#to_date_picker').datepick(
dateFormat: 'dd-mm-yy'
);
You can use new DateTime($todate); if you have PHP 5 >= 5.2.0 which is easier to use in my own opinion. Or if you don't want tu change the format return by your JavaScript, use the method DateTime::createFromFormat('j-M-Y', '15-Feb-2009'); which returns a DateTime object from a "custom" date (see documentation, link below).
Link : http://www.php.net/manual/fr/datetime.construct.php
http://www.php.net/manual/fr/datetime.createfromformat.php

Categories

Resources