How to compare date with current date for applying logic - javascript

<script>
$(document).ready(function(){
if(date.now()>($("[id$=clear2]").val)+2){
$("[id$=clear]").val("");
$("[id$=clear2]").val("");// date value
$("[id$=clear3]").val("");
}
});
</script>
I want to check that current date(dd/mm/yyyy) is greater than date(dd/mm/yyyy) value + 2 days .I was working several scenarios .that by removing if condition it is working fine .By using this it is not working well .Can you show some solution so that i can move forward

Try this:
var d1 = '31/11/2015'.split('/');
var d2 = '27/12/2015'.split('/');
var date1 = new Date(d1[2],d1[1],d1[0]); // YYYY,MM,DD
var date2 = new Date(d2[2],d2[1],d2[0]);
var numOfDaysToAdd = 2;
date2.setDate(date2.getDate() + numOfDaysToAdd);
if (date1.getTime() < date2.getTime()) {
alert('date1 is before date2');
}

Working with dates in javascrip:
javascript
$(document).ready(function () {
var today = new Date();
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
$("#today").val(today.toUTCString());
$("#tomorrow").val(tomorrow.toUTCString());
$("#checkDate").click(function () {
var newDate = new Date($("#today").val());
newDate.setDate(newDate.getDate() + 2);
var parsedTomorrow = new Date($("#tomorrow").val());
var comRes = newDate > parsedTomorrow;
alert(comRes);
});
});
HTML
<input type="text" id="today" />
<input type="text" id="tomorrow" />
<input type="button" id="checkDate" />
DEMO

Use JavaScript Date Object to compare dates in javascript.

Related

Dynamic date Caluculation in Java script

I Am having two dataPickers of dijit/form/DateTextBox. One for startdate and another one for Enddate.
I want to check whether "Enddate > startdate+ 90days 3month)", if yes then I need to reset the end-date with startdate+ 90days.
format which am getting from DateTextBox 2018-04-25. Please help on this
var fromDate=digit.byId('startDate');
if(fromDate!=null) {
var fromtimestamp=new Date(digit.byId('startDate')).getTime();
var endtimestamp=new Date(digit.byId('endDate')).getTime();
var timestamp= new Date(digit.byId('startDate')).getTime+ (30 *24*60*60*1000);
if(endtimestamp>timestamp) {
// wants to reset with startdate+ 90days
}
}
You can achieve this but using dateBox min constaraint setting a change event in your start date , then set the digit.byId('endDate').constraints.min start date + 90
as :
digit.byId('startDate').on("change",function() {
var end = new Date(this.value);
end.setDate(end.getDate() + 90);
digit.byId('endDate').constraints.min = end;
})
See below programmatic snippet :
require(["dijit/form/DateTextBox", "dijit/form/Button","dojo/on" ,
"dojo/domReady!"
], function(DateTextBox,Button, On ) {
var startdate = new DateTextBox({
constraints:{
datePattern:'yyyy-MM-dd'
}
}, "startDate");
var enddate = new DateTextBox({
constraints:{
datePattern:'yyyy-MM-dd'
}
}, "endDate");
startdate.on("change",function() {
var end = new Date(this.value);
end.setDate(end.getDate() + 90);
enddate.constraints.max = end;
enddate.constraints.min = new Date(this.value);
})
});
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<body class="claro">
start :<div id="startDate" ></div>
end : <div id="endDate" ></div>
</body>

Changing a ISO date to a Short date JavaScript

I currently have a function setup to get the following two weeks or months from the selected date from a input date field. However, the problem I'm facing is that I want to get the date to output DD/MM/YYYY but I'm getting the full ISO date where I need the short. Does anyone know how I can go about doing this?
EDIT:
I've added the moment(date1).format('DD/MM/YYYY'); to test the code but this hasn't provided any results.
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
moment(date1).format('DD/MM/YYYY');
var date2 = new Date(date1);
date2.setMonth(date2.getMonth() + 1);
document.getElementById("pM1").innerHTML = date1;
document.getElementById("pM2").innerHTML = date2;
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var date2 = new Date(date1);
date2.setDate(date2.getDate() + 7);
document.getElementById("pW1").innerHTML = date1;
document.getElementById("pW2").innerHTML = date2;
}
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
First off, you are setting the input value to the current date right here
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
don't do that, it kind of defeats the purpose of having a selector in the first place.
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US" as the locale:
console.log((new Date()).toLocaleDateString('en-US')); // format MM/DD/YYY
I also fixed how you set the new dates, it now takes one date and adds either one and two months or one and to weeks instead of none and one month and none and one week ;-)
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate;
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setMonth(date1.getMonth() + 1);
var datePlusTwo = new Date(date1);
datePlusTwo.setMonth(date1.getMonth() + 2);
document.getElementById("pM1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pM2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setDate(date1.getDate() + 7);
var datePlusTwo = new Date(date1);
datePlusTwo.setDate(date1.getDate() + 14);
document.getElementById("pW1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pW2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
}
}
.hidden {
display: none;
}
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
Instead of document.getElementById("pM1").innerHTML = date1; you should build first a string with the methods provided by the date object ( getFullYear, getDate, getMonth; see docu ). Then you can assign the string to the innerHtml.
If you can use the moment.js then your code which you assign to your innerHtml is date1 = moment(dateSelected).format('DD/MM/YYYY')
Also I would recommend Luca's way:
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US"
which would look at your code:
dateSelected.toLocaleDateString('en-US')
You could use MomentJS library to keep things simple:
Include the library :
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
document.getElementById("pM1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pM2").innerHTML = moment(date2).format('DD/MM/YYYY');
and in the else:
document.getElementById("pW1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pW2").innerHTML = moment(date2).add(1, 'week').format('DD/MM/YYYY');

How to stop incorrect value in datepicker when previous data select in JavaScript?

Here, I got code for disable date in datepicker. when user select previous date then it alert to put a valid future date. It's working.
But It's printing whatever we select previous date. I want to stop print when previous date select. Thanks in advance.
<div class="col-md-8">
<input class="form-control datepicker" id="datepicker" onchange="checkDate()" required type="date" name="smexdate" value="<?=$promotion_details['expiry_date']?>" data-date-format="yyyy-mm-dd">
</div>
and JavaScript below.
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
alert("Date must be in the future");
return false;
}
}
How about this?
var lastData;
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedField = document.getElementById('datepicker');
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
console.log(lastData)
selectedField.value = (lastData) ? lastData : '';
alert("Date must be in the future");
return 0;
}
var theDate = new Date(selectedText);
var month = theDate.getMonth() + 1;
var date = theDate.getDate();
var year = theDate.getFullYear();
lastData = year + "-" + String("0" + month).slice(-2) + "-" + String("0" + date).slice(-2);
}

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

At the submit button start time and end time to be calculate by javascript

i have tried to get start time and end time by java-script but i dono how to get on submit button it have to run on side of submit button how much time to run a Report...
var begin_date = new Date();
//begin_time = begin.date.getTime();
begin_time = begin_date.getMilliseconds();
begin_date2 = begin_date;
var end_date = new Date();
//end_time = end_date.getTime();
end_time = end_date.getMilliseconds();
total_time = end_time - begin_time;
'Begin Time (ms): ' + begin_time;
'End time (ms): ' + end_time + "\n"+' Total time (ms): ' + total_time;
like wise i have to get in javascript ...how to achieve this ?
Here's id the code that myt help ur purpose
$(document).ready(function () {
var datetime = new Date();
var starttime = datetime.getTime();
$('#abc').click(function () {
var datetime1 = new Date();
var endtime = datetime1.getTime();
alert(starttime);
alert(endtime);
var time_diff = starttime - endtime;
alert(time_diff);
});
});
<input type=button value=button id='abc'>
I have created created a demo fiddle for this demo
This script gives how much time Elapsed from start to end (till submit button pressed) - Time is in milliseconds.
SCRIPT:
var begin_date;
var btime1,btime2,btime3,btime;
var etime1,etime2,etime3,etime;
var end_date;
function f1(){
begin_date = new Date();
btime1=begin_date.getHours();
btime2=begin_date.getMinutes();
btime3=begin_date.getSeconds();
}
function f2(){
end_date = new Date();
etime1=end_date.getHours();
etime2=end_date.getMinutes();
etime3=end_date.getSeconds();
total_time = end_date-begin_date;
}
$(document).ready(function(){
$("#b1").click(function(){
f2();
$("#start").val(btime1+":"+btime2+":"+btime3);
$("#end").val(etime1+":"+etime2+":"+etime3);
});
});
HTML:
<body onload="f1()">
<button id="b1">button</button><br/><br/>
START: <input type="text" id="start">
END: <input type="text" id="end" >
</body>

Categories

Resources