compare date entered in textbox with javascript - javascript

asp.net Code:
<div class="form-group">
<label class="control-label col-md-5">Received Date</label>
<div class="col-md-7">
<div class="input-group date date-picker" id="recvdate" data-date-format="dd-mm-yyyy" runat="server">
<asp:TextBox ID="txtRecvdDate" CssClass="form-control tooltips" data-original-title="dd-mm-yyyy" data-placement="top" runat="server"></asp:TextBox>
<span class="input-group-btn">
<button class="btn default dtp-btn " id="Button2" type="button" runat="server"><i class="icon-calendar"></i></button>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-5">Expiry Date</label>
<div class="col-md-7">
<div class="input-group date date-picker" id="expdate" data-date-format="dd-mm-yyyy" runat="server">
<asp:TextBox ID="txtExpiryDate" CssClass="form-control tooltips" onkeyup="validation();" data-original-title="dd-mm-yyyy" data-placement="top" runat="server"></asp:TextBox>
<span class="input-group-btn" id="expiryDatePicker">
<button class="btn default dtp-btn " id="Button1" type="button" runat="server"><i class="icon-calendar"></i></button>
</span>
<asp:Label ID="lblreasonMessagedvTabNavigationAction" Font-Bold="true" runat="server"></asp:Label>
</div>
</div>
</div>
Javascript
function validation() {
var startDate = $("[id*=txtRecvdDate]").val();
var endDate = $("[id*=txtExpiryDate]").val();
var newDate = new Date(startDate);
var newToDate = new Date(endDate);
if (newDate != '' && newToDate !='') {
if (newDate < newToDate)
{
alert("check");
}
}
return false;
}
I am unable the compare the expiry date with received date textbox. In which expiry date should be greater than received date

You have date as dd-mm-yyyy format from textbox(startdate). so when you use it in conversion like new Date(dd-mm-yyyy). It will throw invaliddate. So before converting change its format to yyyy-mm-dd by using below code. because new Date accept datestring in yyyy-mm-dd format.
function validation() {
var startDate = $("[id*=txtRecvdDate]").val();
var newdatestring = startDate.split("-").reverse().join("-");
var newDate= new Date(newdatestring);
var endDate = $("[id*=txtExpiryDate]").val();
var newToDatestring = endDate.split("-").reverse().join("-");
var newToDate= new Date(newToDatestring);
if (newDate != '' && newToDate !='') {
if (newDate < newToDate)
{
alert("check");
}
}
return false;
}
Note: If you are using / instead of - then replace - with / in the above code

Related

Comparing two custom format dates jquery

I have tried to validate my dates if start date is less than end date it should alert but it only work with in same month, but when i compare dates of one month date to another month date it keeps stops me select less date even it is already.
here is what i have done so far,
$('#datepicker2').change(function () {
var startDate = new Date($('#datepicker').val());
var endDate = new Date($('#datepicker2').val());
if (startDate < endDate){
alert("selected date is above pickup date, ");
}
});
here is my html
<div class="col-md-4">
<div class="row">
<div class="col-md-6">
<input type="text" id="datepicker" required name="pickupDate" placeholder="Pickup Date">
</div>
<div class="col-md-6">
<input class="" id="datetimepicker4" autocomplete="off" required name="pickupTime" placeholder="Pickup Time">
</div>
</div>
</div>
<div class="col-md-4">
<div class="row ct-date-row">
<div class="col-md-6">
<input type="text" id="datepicker2" required name="dropDate" placeholder="Drop off Date">
</div>
<div class="col-md-6">
<input class="" autocomplete="off" id="datetimepicker5" required name="dropTime" placeholder="Drop Time">
</div>
</div>
</div>
my date format is d/m/y if this is making issue then how could i possibly define formate within new date and compare them. Thanks
I want when same date it hides previous time on time drop down of jquery.
$('#datetimepicker5').timepicker({
timeFormat: 'HH:mm',
});
$('#datetimepicker4').timepicker({
timeFormat: 'HH:mm',
});
format of my time i am not being to get time which is selected,
jQuery('document').ready(function(){
jQuery('#datetimepicker5').on('change paste keyup', function() {
var x = jQuery("#datetimepicker5").val();
alert(x);
});
});
So, you are using jQuery Ui DatePicker, there is native way to get date with getDate, here you go:
For compare your dates if equal or same you need to use Date.parse() , you need to do this:
if (Date.parse(startDate) === Date.parse(endDate))
$(function() {
$("#datepicker").datepicker({
dateFormat: "d/m/y"
});
$("#datepicker2").datepicker({
dateFormat: "d/m/y"
});
$('#datetimepicker5').timepicker({
timeFormat: 'HH:mm',
});
$('#datetimepicker4').timepicker({
timeFormat: 'HH:mm',
});
});
$('#datepicker2').on('paste keyup change', function() {
var startDate = $('#datepicker').datepicker("getDate");
var endDate = $('#datepicker2').datepicker("getDate");
if (startDate > endDate) {
alert("selected date is above pickup date, ");
} else if (Date.parse(startDate) === Date.parse(endDate)) {
alert("same");
var dt = new Date();
var phours = dt.getHours() + 3;
var time = phours + ":" + "00";
alert(time);
jQuery('#datetimepicker5').timepicker({
minTime: time
});
jQuery('#datetimepicker4').timepicker({
minTime: time
});
$('#datetimepicker4').val(time)
$('#datetimepicker5').val(time)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://www.jonthornton.com/jquery-timepicker/jquery.timepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha256-KM512VNnjElC30ehFwehXjx1YCHPiQkOPmqnrWtpccM=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha256-rByPlHULObEjJ6XQxW/flG2r+22R5dKiAoef+aXWfik=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.min.css" integrity="sha256-zV9aQFg2u+n7xs0FTQEhY0zGHSFlwgIu7pivQiwJ38E=" crossorigin="anonymous" />
<div class="col-md-4">
<div class="row">
<div class="col-md-6">
<input type="text" id="datepicker" required name="pickupDate" placeholder="Pickup Date">
</div>
<div class="col-md-6">
<input class="" id="datetimepicker4" autocomplete="off" required name="pickupTime" placeholder="Pickup Time">
</div>
</div>
</div>
<div class="col-md-4">
<div class="row ct-date-row">
<div class="col-md-6">
<input type="text" id="datepicker2" required name="dropDate" placeholder="Drop off Date">
</div>
<div class="col-md-6">
<input class="" autocomplete="off" id="datetimepicker5" required name="dropTime" placeholder="Drop Time">
</div>
</div>
</div>
You can convert your both dates to seconds and then compare it. then it will work like charm:
i.e.
var date1 = new Date("2015-08-25T15:35:58.000Z");
var seconds1 = date1.getTime() / 1000; //1440516958
Use Date.parse()
The Date.parse() method parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
$('#datepicker2').change(function () {
var startDate = new Date($('#datepicker').val());
var endDate = new Date($('#datepicker2').val());
if (Date.parse(startDate) < Date.parse(endDate)){
alert("selected date is above pickup date, ");
}
});

Want to calculate date of birth from a given age

I'm trying to calculate the date of birth from a given age.
My logic is
When we enter an age say '5'. The date of birth will be calculated as exactly 5 years from the current date. Example current date is 20/8/2018.
Then date of birth will be 20/8/2013 if the age is 5.
So below is my code:
function validatedob() {
var dob_value = document.getElementById('dob').value;
var age_value = document.getElementById('age').value;
var current_date = new Date();
var birth_date = new Date();
var birth_year = current_date.getFullYear() - age_value;
var birth_month = current_date.getMonth();
var birth_day = current_date.getDate();
birth_date.setDate(current_date.getFullYear() - age_value);
birth_date.setMonth(current_date.getMonth());
birth_date.setFullYear(current_date.getDate());
document.getElementById('dob').setDate(birth_day);
document.getElementById('dob').setMonth(birth_month);
document.getElementById('dob').setFullYear(birth_year);
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
This is not working. I'm not goodwith html properties.
Can someone help me? how to achieve this?
Here is the simple answer:
> d1 = new Date(2018, 00, 01)
Date 2018-01-01T00:00:00.000Z
> d2 = new Date(d1.getFullYear() - 5, d1.getMonth(), d1.getDate())
Date 2013-01-01T00:00:00.000Z
But, I would suggest to use a library such as Luxon.
Date manipulation is an absolute nightmare if you do it by yourself. This video from Computerphile summarizes it better than I could:
https://www.youtube.com/watch?v=-5wpm-gesOY
Here is a really simple solution that works and some changes to your HTML.
Changes to HTML:
The div and label both had the id "age", this must be unique.
type="integer"doesn't exist, so i changed it to type="number".
And value="unknown"isn't the right format "yyy-MM-dd", so i just removed it.
for="DOB"to for="dob", now that works aswell
Code:
HTML
<div class="form-inline">
<label for="age">Age</label>
<input id="age" type="number" name="age"onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="dob">Date of Birth</label>
<input id="dob" type="date" name="date_of_birth" max="31-12-2030">
</div>
JavaScript
function validatedob() {
var age_value = document.getElementById("age").value;
var current_date = new Date();
var birth_date = new Date(current_date.getFullYear() - age_value, current_date.getMonth(), current_date.getDate() + 1);
document.getElementById("dob").valueAsDate = birth_date;
}
Here is some sample code for your reference
https://codepen.io/ji_in_coding/pen/wEvoMK
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth" >
<label for="DOB">Date of Birth</label>
<input id="dob" type="input" name="date_of_birth">
</div>
Javascript
function validatedob()
{
var age_value = document.getElementById("age").value;
var today = new Date();
var calculated_birthday = new Date(
parseInt(today.getFullYear())+parseInt(age_value),
today.getMonth(),
today.getDate());
document.getElementById("dob").value = calculated_birthday.toLocaleDateString("en-US");
}
You're issue is that you are trying to setDate and cie on a HTMLElement. The input dob expect a string formatted as yyyy-MM-dd. You can try something like that:
var $dob = document.getElementById('dob');
var $age = document.getElementById('age');
function validatedob() {
var age = $age.value;
var date = new Date();
date.setFullYear(date.getFullYear() - age);
$dob.value = formatDate(date);
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
PS: For performance purpose avoid to repeat document.getElementById(...) in each method call. Do it once as done in my example.

Could not diferentiate the date using the javascript [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 4 years ago.
I am facing one problem. I am unable to differentiate the date difference using the javascript. I am explaining my code below.
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day=1000*60*60*24;
var x=startdate_val.split("-");
var y=enddate_val.split("-");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;
var date_diff = Math.ceil((date2.getTime()-date1.getTime())/(one_day));
console.log('date',date_diff <= 0);
Here I need enddate always should be greater than the start date. Here I am attaching my datetime code.
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="" placeholder="17-06-2017"/>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="" placeholder="17-06-2017"/>
</div>
</div>
</div>
Here I am getting the date field value like this i.e-03-01-2018 02:46. I need always the end date time should be greater than the start date time but in my case in console message always I am getting the result false.
Try this:
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="17-06-2017" placeholder="17-06-2017"/>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="17-07-2017" placeholder="17-06-2017"/>
</div>
</div>
</div>
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day=1000*60*60*24;
var x=startdate_val.split("-");
var y=enddate_val.split("-");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;
var date_diff = Math.ceil((date2.getTime()-date1.getTime())/(one_day));
console.log(date_diff >= 0);
You just need to change the line: console.log('date',date_diff <= 0);
Simply do like this :
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var stdate = new Date(startdate_val).toISOString();
var enddate = new Date(enddate_val).toISOString();
//Then
Console.log(enddate >= stdate);
Sample Code that I've tried:
var startdate_val = '01-03-2018 02:45';
var enddate_val = '01-03-2018 02:45';
var stdate = new Date(startdate_val);
var enddate = new Date(enddate_val);
//Then
alert(enddate >= stdate);
Returns True
Fiddle
Converting the string to Date Object will be better than the manual labor.
in your HTML code, there is no value so you can't compare it to page load time, because it is blank.
somehow if you are using any click functionality then
please update your code below.
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day = 1000 * 60 * 60 * 24;
var x = startdate_val.split("-");
var y = enddate_val.split("-");
var date1 = new Date(x[2], (x[1] - 1), x[0]);
var date2 = new Date(y[2], (y[1] - 1), y[0])
var month1 = x[1] - 1;
var month2 = y[1] - 1;
var date_diff = Math.ceil((date2.getTime() - date1.getTime()) / (one_day));
if (date_diff <= 0)
console.log(false);
else
console.log(true);
AND HTML FOR PAGE LOAD
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="17-06-2017" placeholder="17-06-2017" />
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="18-06-2017" placeholder="17-06-2017" />
</div>
</div>
</div>

Datetimepicker bootstrap not working proberly in asp.net website

I could use some eyes to check what i have done wrong with this code. I have tried to follow an example where i have made to input boxes for check-in and check-out.
It look like this:
Check-in
Input box (datetimepicker1)
Check-out
Input box (datetimepicker2)
I'm trying to make it so when you pick a date in datepicker1, you can pick an earlier date with the datetimepicker2 form. You have to pick a day at least 1 day ahead.
My asp code:
<div class="form-group">
<div class="input-append date form_datetime">
<asp:Label ID="Label1" runat="server" Text="Check-in Date:"></asp:Label>
<input type="text" class="form-control" id="datetimepicker1" />
</div>
</div>
<div class="form-group">
<div class="input-append date form_datetime">
<asp:Label ID="Label2" runat="server" Text="Check-out Date:"></asp:Label>
<input type="text" class="form-control" id="datetimepicker2" />
</div>
</div>
Javascript:
<script type="text/javascript">
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#datetimepicker1').datepicker({
onRender: function (date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
}
checkin.hide();
$('#datetimepicker2')[0].focus();
}).data('datepicker');
var checkout = $('#datetimepicker2').datepicker({
onRender: function (date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');
</script>
I'm sure that i got the right js files in, because it have worked with some other code before, but it was not that smart, because i don't want any icons, it should only be a text box, and when u click on it, the datetimepicker should open it self.
Hope someone can see what is wrong with this.

bootstrap linked datetime picker not working properly

hi i am trying to develop bootstrap jquery for linked datetime pickers but is not working correctly am using jsfiddle http://jsfiddle.net/srknthcse/CujDK/311/ i have selected No-library ...any help will be appreciated .thank you
<div class="container">
<div class='col-md-5'>
<div class="form-group">
<div id="startdatetime-from" class="input-append date">
<input type="text" id="datetimepicker-input" readonly ></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
<div class='col-md-5'>
<div class="form-group">
<div id="startdatetime-from1" class="input-append date1">
<input type="text" id="datetimepicker-input1" readonly ></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
</div>
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
var hours= d.getHours();
var minutes=d.getMinutes();
$(function() {
$('#startdatetime-from').datetimepicker({
language: 'en',
showMeridian:'true',
autoclose:'true',
format: 'hh:mm PP dd-MM-yyyy '
});
$("#startdatetime-from").data('datetimepicker').setLocalDate(new Date(year, month, day, hours, minutes));
var d1=new Date();
var d2=new Date(d1);
var addedhour=d2.setHours(d1.getHours()+4);
$('#startdatetime-from1').datetimepicker({
language: 'en',
showMeridian:'true',
autoclose:'true',
format: 'hh:mm dd-MM-yyyy '
});
$("#startdatetime-from1").data('datetimepicker').setLocalDate(new Date(year, month, day, hours, minutes));
$("#startdatetime-from").on("dp.change", function (e) {
$('#startdatetime-from1').data("DateTimePicker").minDate(e.date);
});
$("#startdatetime-from1").on("dp.change", function (e) {
$('#startdatetime-from').data("DateTimePicker").maxDate(e.date);
});
});
<div class="container">
<div class='col-md-10'>
<div class="form-group">
<div id="startdatetime-from" class="input-append date">
<input type="text" id="datetimepicker-input" readonly></input>
</div>
<div></div>
<div class='col-md-10'>
<div class="form-group">
<div id="startdatetime-from1" class="input-append date1">
<input type="text" id="datetimepicker-input1" readonly></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
</div>
</div>
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
var hours = d.getHours();
var minutes = d.getMinutes();
$(function () {
$('#startdatetime-from').datetimepicker({
language: 'en',
autoclose: 'true',
format: 'HH:mm PP dd-MM-yyyy '
});
$("#startdatetime-from").data('datetimepicker').setLocalDate(new Date(year, month, day, hours, minutes));
$('#startdatetime-from1').datetimepicker({
language: 'en',
autoclose: 'true',
format: 'HH:mm PP dd-MM-yyyy '
});
$("#startdatetime-from1").data('datetimepicker').setLocalDate(new Date(year, month, day, hours+4, minutes));
});

Categories

Resources