Get the date value in mm/dd/yyyy format in javascript - javascript

If i am entering a date in first text box i need to get the duration in second textbox by taking the differece with
current date, i do somting its working fine only with dd/mm/yyyy format,but i need to enter the date in mm/dd/yyyy format. my working Code will be here please help me
<input type="text" name"mydate" id="mydate" placeholder="mm/dd/yyyy">
<input type="text" name="duration" id="duration">
<script>
function getYearFn()
{
from = $("#mydate").val().split("/");
var fromdate = new Date(from[2], (from[1]-1), from[0]);
var today = new Date();
var year1 = fromdate.getFullYear();
var year2 = today.getFullYear();
var yeardiff = year2 - year1;
var month1 = fromdate.getMonth()+1;
var month2 = today.getMonth()+1;
var monthdiff = (month1 - month2)*-1;
$('#duration').val(yeardiff +" " +"Years"+" "+monthdiff*-1 +""+"Months" )
}
</script>

You only have to interchange the parameters in the date creation.
Instead of
var fromdate = new Date(from[2], (from[1]-1), from[0]);
use
var fromdate = new Date(from[2], (from[0]-1), from[1]);

Related

How setattribute value input date?

How would you set the value adding day+1 from the current date in JavaScript?
I have this:
<input type="date" id="mycalendar" >
try to set value:
var datedft = document.getElementById('mycalendar').value;
var date = new Date(datedft);
var newdate = new Date(date);
newdate.setDate(newdate.getDate());
var dd = newdate.getDate();
var mm = newdate.getMonth() + 2;
var y = newdate.getFullYear();
var newformat =y+'-'+mm+'-'+dd ;
document.getElementById('mycalendar').value = newformat
In my console Browser I got:
The specified value "2020-10-1" does not conform to the required
format, "yyyy-MM-dd".
The required format is "yyyy-MM-dd", so your date string value should be "2020-10-01".
var newFormat = y.toString().padStart(4, '0') + '-' + mm.toString().padStart(2, '0') + '-' + dd.toString().padStart(2, '0');
If the date format is absolutely critical to the functioning of the webpage, then we will need to make that choice. Below is a code snippet with the date format altered to the YYYY-MM-DD format.
<input type="text" name="input" placeholder="YYYY-MM-DD" required
pattern="(?:19|20)\[0-9\]{2}-(?:(?:0\[1-9\]|1\[0-2\])-(?:0\[1-9\]|1\[0-9\]|2\[0-9\])|(?:(?!02)(?:0\[1-9\]|1\[0-2\])-(?:30))|(?:(?:0\[13578\]|1\[02\])-31))" />
I believe you're asking how to get the correct format when the day(getDate()) is less than 10.
var datedft = document.getElementById('mycalendar').value;
var date = new Date(datedft);
var newdate = new Date(date);
newdate.setDate(newdate.getDate());
var dd = newdate.getDate();
var updatedDD = dd >= 10 ? dd : `0${dd}`; // updated line
var mm = newdate.getMonth() + 2;
var y = newdate.getFullYear();
var newformat =y+'-'+mm+'-'+updatedDD ; // updated line
document.getElementById('mycalendar').value = newformat
I think you want to add one day to the date which user has selected. please check the code snippet.
function onChangeDate() {
var datedft = document.getElementById('mycalendar').value;
var date = new Date(datedft);
date.setDate(date.getDate() + 1)
var newformat = date.toISOString().substr(0, 10)
document.getElementById('mycalendar').value = newformat
}
<input type="date" id="mycalendar" onchange='onChangeDate()'>
The below code will set the next day date in "mycalendar"
const today = new Date(); // today's date
const tomorrow = new Date(today.setDate(today.getDate() + 1)); // tomorrow's date
document.getElementById('mycalendar').value = tomorrow.toISOString().split('T')[0];
<input type="date" id="mycalendar" >

Date difference issue in moment

I am trying to create a new Date using 2 dates I have. Basically my new date
Output:
Date 1 = (presentdate +1 month , endDate+1 day, presentdate+1 year);
//Example 1:
var presentDate = "11/12/2018";
var endDate = "2/8/2018";
var Dat1 = "12/9/2018"; //new date
//Example 2 :
var presentDate = "11/12/2018";
var endDate = "5/25/2018";
var Dat1 = "12/26/2018"; //new date
//Example 3 :
var presentDate = "1/5/2018";
var endDate = "5/30/2018";
var Date1 = "2/31/2018"; // invalid date
//should've been 2/28/2018 since that is the last day of the month
//Example 4:
var presentDate = "3/5/2018";
var endDate = "10/30/2018";
var Date1 = "4/31/2018"; //Invalid date. Should've been 4/30/2019 since it's last day of the month
My code:
var mPresent = moment(presentDt);
var mEnd = moment(eDt);
var Date1 = moment({
year: mPresent.year(), // get presentDt's year
month: mPresent.add(1, 'month').month(), // get presentDt's month
date: mStart.date() // get startdt day of the month
});
console.log(Date1);
It doesn't work in all cases because not every month have 30,31 days and then there is the leap year. I need to create a date that is valid because in some of these cases it returns invalid date.
Any help is appreciated. Thank you!
I'm not entirely sure what's going on with your code, but I chopped out most of it and basically did a 1-liner to calculate the # of months difference - seems to work.
document.querySelector("#ok").addEventListener("click", function () {
var paymentDate = document.getElementById("presentDate").value;
var etDate = document.getElementById("endDate").value;
var RemainingPayments = moment(etDate).diff(moment(paymentDate), 'months');
console.log(RemainingPayments);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<label>Present date</label><input id="presentDate" name="presentDate" type="date">
<label>End Date</label> <input id="endDate" name="endDate" type="date">
<button id='ok'>OK</button>

How can I calculate the 2 datetime picker?

I have 2 datetimepickers and I want to know to calculate the day or time.
Ex:
2017-01-12 09:00:00
2017-01-12 10:00:00
The answer should be 1:00:00
Below is my code. I also wanna know the date time formatting for this.
<input required type="text" class="form-control" id="time_in">
<input required type="text" class="form-control" id="time_out">
$start_time = $("#time_in").val();
$end_time = $("#time_out").val();
$answer = date_diff($start_time, $end_time)
alert($start_time);
This will do what you want to achieve.
Try:
old_date = "2010-11-10 07:00:00";
new_date = "2010-11-10 08:00:00";
old_date_obj = new Date(Date.parse(old_date, "dd/mm/yyyy HH:mm:ss"));
new_date_obj = new Date(Date.parse(new_date, "dd/mm/yyyy HH:mm:ss"))
t = (new_date_obj - old_date_obj);
seconds=(t/1000)%60
minutes=(t/(1000*60))%60
hours=(t/(1000*60*60))%24
alert(hours+":"+minutes+":"+seconds)
probably want something like
function date_diff(start, end)
{
var d1 = new Date(start);
var d2 = new Date(end);
return d2-d1;
}
note that the answer here is in miliseconds
var date;
date = new Date("$start_time);
var startTime = date.getTime();
date = new Date("$end_time);
var endTime = date.getTime();
var difference=startTime-endTime;
var answer= new Date(difference);
Hope this Helps.

Date function in JS, comparing with a set date not working

I have to pretty much validate and check if the user is underage in ASP. So anyone under the age of 01/07/1998 is underage. I have 3 dropdown lists to select date, month and year. Im using JS. I try using concat and split but they dont work. Can anyone help with this?
function ValidateDate() {
var dDay = document.getElementById('DateList');
var dMonth = document.getElementById('MonthList');
var dYear = document.getElementById('YearList');
var day = dDay.selectedIndex;
var month = dMonth.selectedIndex;
var year = dYear.selectedIndex;
var firstValue = year + month + day;
var setyear = "1998";
var setmonth = "06";
var setdate = "01";
var secondValue = setyear + setmonth + setdate;
var firstDate = new Date();
firstDate.setFullYear(firstValue[0], (firstValue[1] - 1), firstValue[2]);
var secondDate = new Date();
secondDate.setFullYear(secondValue[0], (secondValue[1] - 1), secondValue[2]);
if (firstDate > secondDate) {
alert("Pass");
}
else {
alert("Fail");
}
}
<asp:CustomValidator ID="CustomValidatorDate" runat="server"
ErrorMessage=" You are underage" CssClass="error" Display="Dynamic" ClientValidationFunction="ValidateDate" ></asp:CustomValidator>
First of all your day, month and year variables are reading the index of the drop-downs and not their values.
For instance, you need to use:
var day = dDay.value,
month = dMonth.value,
year = dYear.value;
And then create date object as
var firstDate = new Date(year, month, day);
-Dipen

Datepicker on AngularJS error with values

The thing I'm trying to do here is when a user selects a StartDate and an EndDate when he clicks on the previous arrow he should fetch data 7 days before every time in order to see the progress.
JavaScript:
$scope.getDiffPrev = function(startDate, endDate, computeDiff) {
var start = startDate;
var date1 = (start.getDate() -7);
var month1 = (start.getMonth() +1);
var year1 = start.getFullYear();
var end = endDate;
var date2 = (end.getDate() -7);
var month2 = (end.getMonth() +1);
var year2 = end.getFullYear();
$http.get('/admin/api/stats?start=' + date1 +'-'+ month1 +'-'+ year1 + '&end=' + date2 +'-'+ month2 +'-'+ year2 +'&computeDiff=true').success(function(data) {
$scope.stats = data;
});
}
HTML:
<label>From</label>
<input type="text" datepicker-popup="dd-MM-yyyy" ng-model="startDate"/>
<label>To</label>
<input type="text" datepicker-popup="dd-MM-yyyy" ng-model="endDate"/>
<button class="btn btn-success" ng-click="getDiffPrev(startDate, endDate, computeDiff)">←</button>
don't we all love javascript's date? ;)
var start = angular.copy(startDate)
start.setDate(start.getDate() + computeDiff);
var date1 = start.getDate();
var month1 = start.getMonth() + 1; // i hate em for this one -.-
var year1 = start.getFullYear();
and here an example
in the line start.setDate(start.getDate() + computeDiff); we use the Date()'s intern calculation to get the right date.
EDIT:
if you can add other libraries have a look at moment.js
moment().subtract('days', 7).format('yourFormatStringHere')

Categories

Resources