I want to restrict date for fifteen days only, I have written some code but don't know where I am going wrong. If anyone can guide me it would be helpful.
this is my full code, I am applying condition also to check if date is greater then 15 but it's not working
<body>
<form>
<div class="container">
<h4>Start Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()" />
<h4>End Date:</h4>
<input type="text" id="enddate" name="todate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()"/>
</div>
<input type="submit" value="submit">
</form>
<script>
var today = new Date(new Date().getFullYear(), new Date().getMonth(),
new Date().getDate());
$('#startdate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
maxDate : function() {
return $('#enddate').val();
}
});
$('#enddate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
minDate : function() {
return $('#startdate').val();
}
});
//function to check wether date is more than 15 its not workin
//all plugins are there u just have to run
function checkDate(){
var start = $('#startdate').val();
var end = $('#enddate').val();
//convert strings to date for comparing
var startDate = new Date(start);
var endDate = new Date(end);
// Calculate the day diffrence
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));
if(diffDays > 15){
alert("Days are more then fifteen");
}
}
</script>
</body>
</html>
here is the fiddle
It's because your datepicker has format dd/mm/yyyy but Date constructor converts it as if it was mm/dd/yyyy.
var date = '01/03/2018'
var d = new Date(date);
console.log(d.toString())
You need to adapt your code to work with dd/mm/yyyy format
function checkDate(start, end){
//convert strings to date for comparing
var startDate = createDate(start);
var endDate = createDate(end);
// Calculate the day diffrence
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));
if(diffDays > 15){
console.log("Days are more then fifteen");
} else {
console.log("Less than 15 days")
}
}
function createDate(datestr){
var datearr = datestr.split("/");
var d = new Date(datearr[2], Number(datearr[1]) - 1, datearr[0])
return d;
}
checkDate("01/02/2018", "10/02/2018")
checkDate("01/02/2018", "30/02/2018")
jsfiddle
The issue is with the date format you're using. 'dd/mm/yyyy' is not a format Date.parse() can handle.
String value representing a date. The string should be in a format
recognized by the Date.parse() method
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters
So you can either change the format to 'mm/dd/yyyy' or you can use moment.js to handle your date manipulations.
If you prefer to stick with the same format and Date library, then you have a solution here
PS: I noticed you have asked the same question before and having issues with the accepted answer. When this happens, please comment on the answer instead of making a duplicate
Look at this answer, here I have used a moment.js library also. this will restrict to 15 days. Hope this sample will give you a solution
$(document).ready(function(){
$('#date-of-ending').datepicker({
autoclose: true,
format:"dd/mm/yyyy"
})
$('#date-of-starting').datepicker({
autoclose: true,
format:"dd/mm/yyyy"
}).on('changeDate', function (selected) {
var xDays = 15;
var selectedDate = moment(selected.date,"DD/MM/YYYY").format("MM/DD/YYYY")
var maxDate = moment(selectedDate.valueOf()).add(xDays, 'days').format('DD/MM/YYYY'); // This is from moment js library
$('#date-of-ending').datepicker('setEndDate', maxDate);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input id="date-of-starting" type="text" name="startDate" value="" readonly class="form-control" required />
<input id="date-of-ending" type="text" name="endDate" value="" readonly class="form-control" required />
Related
I am having fromdate and todate I want if user enters the from date and to date the gap between them should not be ore then 20 days. i.e if user enters from date='30/08/2018' to date='26/09/2018' here the gap is more then 20 days so i want to show a alert using jquery.
Below is my code
var today = new Date(new Date().getFullYear(), new Date().getMonth(),new Date().getDate());
$('#startdate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
maxDate : function() {
return $('#enddate').val();
}
});
$('#enddate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
minDate : function() {
return $('#startdate').val();
}
});
handle onchanged event in both the inputs and make a function 'checkDates()' which will compare the two dates and if the difference is more then 20 days make alert() .See the example code below
<input id="startdate" onchanged="checkDate()"/>
<input id="enddate" onchanged="checkDate()"/>
<script>
function checkDate(){
var start = $('#startdate').val();
var end = $('#enddate').val();
//convert strings to date for comparing
var startDate = new Date(start);
var endDate = new Date(end);
// Calculate the day diffrence
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));
if(diffDays > 20){
alert("Days are more then twenty");
}
}
</script>
Please let me know if it worked.
Try this.....
<input id="startDate" onchanged="myFunction()"/>
<input id="endDate" onchanged="myFunction()"/>
<script>
function myFunction(){
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if(diffDays > 20){
alert("Days are more then twenty");
}
}
</script>
Given is an ionic app with <input type='datetime-local'> inputs which runs on an android system. The problem ist that the inputs have different formats after the user selects a Dates. Start is after the user selected a date and Ende is the default formatting. I already tried to add the min, max and step attribute.
The format without the miliseconds is the preferred one.
The Controller
$scope.event = {};
// Default dates
$scope.event.start = new Date();
$scope.event.end = new Date();
$scope.event.end.setHours($scope.event.start.getHours() + 2);
The HTML Part
<label class="item item-input underlinedInput equal-padding ">
<span class="input-label">Start</span>
<input type="datetime-local" placeholder="Start" ng-model="event.start" step="1" min="1900-01-01T00:01:00" max="2900-01-01T23:59:59">
</label>
<label class="item item-input underlinedInput equal-padding ">
<span class="input-label">Ende</span>
<input type="datetime-local" placeholder="Ende" ng-model="event.end" step="1" min="1900-01-01T00:01:00" max="2900-01-01T23:59:59">
</label>
For anyone interested, i wrote a factory that solves my problem.
Instead of creating a date like $scope.event.start = new Date() just use $scope.event.start = Tools.currentDate();
.factory('Tools', function () {
return {
utcDate: function (date) {
var d = new Date(date.replace(' ', 'T'));
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
return d;
},
currentDate: function () {
var d = new Date();
var year = d.getFullYear();
var month = this.leadingZero(d.getMonth());
var day = this.leadingZero(d.getDate());
var hour = this.leadingZero(d.getHours());
var minutes = this.leadingZero(d.getMinutes());
return this.utcDate(year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00");
},
leadingZero: function(number){
return ("0"+number).substr(-2,2);
}
}
})
use date object like
$scope.event.start = new Date(2010, 11, 28, 14, 57);
refer this plunker
you can use moment JS and you will have a better control over date manipulation in your app. moment js docs
var startDate = moment().format('DD/MM/YYYY, HH:MM A');
var endDate = moment().add(2, 'hours').format('DD/MM/YYYY, HH:MM A')
I have a start-date and end-date and I want to calculate array of dates between these days based on a given duration.
for example,
if start date is 01/01/2015 and end date is 01/06/2015 and if I give duration as 3 months then out put should be:
01/04/2015
01/06/2015
How to achieve this using JavaScript and I need to display it in a form.
If you want to calculate difference between two dates using javascript:
Then,
function dateDiff() {
var dtFrom = document.getElementById('txtFromDate').value;
var dtTo = document.getElementById('txtToDate').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getTime() - dt1.getTime();
var days = diff/(1000 * 60 * 60 * 24);
alert(dt1 + ", " + dt2);
alert(days);
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
}
HTML:
<label for="txtFromDate">From Date : </label>
<input type="text" id="txtFromDate" name="txtFromDate" size="10" maxlength="10" value="03/25/2013"/><br/>
<label for="txtToDate">To Date : </label>
<input type="text" id="txtToDate" name="txtDate" size="10" maxlength="10" value="03/26/2013"/><br/>
<button id="btnCheck" name="btnCheck" onClick="dateDiff();" type="button">Difference</button>
AFTER EDIT:
Following solution is to get all dates between specified dates.
Working Demo
// using Datepicker value example code
$('#getBetween').on('click', function () {
var start = $("#from").datepicker("getDate"),
end = $("#to").datepicker("getDate");
var between = getDates(start, end);
$('#results').html(between.join('<br> '));
});
// This function doing this work.
function getDates(start, end) {
var datesArray = [];
var startDate = new Date(start);
while (startDate <= end) {
datesArray.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return datesArray;
}
I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle
im using bootstrap-datetimepicker from http://tarruda.github.io/bootstrap-datetimepicker/
this gives the option to select the datetime in local time, what i cannot understand is how do i convert it to UTC before sending it to the cgi. I need to do this because my server is set at GMT timezone and the input can come in from any timezone.
so i would like the user to select the time in his tz but convert that selection to gmt which sending it to my cgi script.
if there is any other better way of solving this issue also i would appreciate it.
<script type="text/javascript">
$('#timetime').datetimepicker({
maskInput: true,
format: 'yyyy-MM-dd hh:mm',
});
</script>
it is being called in the form in the below code
<label for="sdate" class="control-label">* Scheduled Date (UTC/GMT)</label>
<div id="timetime" class="controls">
<input id="sdate" name="sdate" type="text" placeholder="YYYY-MM-DD HH:MM"></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
final answer based on the help given by filmor
<script type="text/javascript">
$('#timetime').datetimepicker({
maskInput: true,
format: 'yyyy-MM-dd hh:mm',
});
$("form").submit(function(){
// Let's find the input to check
var $input = $(this).find("input[name=sdate]");
if ($input.val()) {
// Value is falsey (i.e. null), lets set a new one, i have inversed this, input should be truthy
//$input.val() = $input.val().toISOString();
var d = $input.val();
var iso = new Date(d).toISOString();
// alert(iso);
$input.val(iso);
}
});
</script>
further update to work on both firefox and chrome
<script type="text/javascript">
$("form").submit(function(){
// Let's find the input to check
var input = $(this).find("input[name=sdate]");
if (input.val()) {
var picker = $('#timetime').data('datetimepicker');
// alert(input.val());
// alert(picker.getLocalDate().toISOString());
input.val(picker.getLocalDate().toISOString());
}
});
</script>
Just use momentjs.
http://momentjs.com/
function getUTCDate() {
return moment($('#sdate').val()).utc().format('YYYY-MM-DDTHH:mm:ssZZ');
}
<script type="text/javascript">
$('#timetime').datetimepicker({
maskInput: true,
format: 'yyyy-MM-dd hh:mm',
});
$("form").submit(function(){
var input = $('#sdate').val();
var input = convertToUtc(input);
});
function convertToUtc(str) {
var date = new Date(str);
var year = date.getUTCFullYear();
var month = date.getUTCMonth()+1;
var dd = dategetUTCDate();
var hh = date.getUTCHours();
var mi = date.getUTCMinutes();
var sec = date.getUTCSeconds();
// 2010-11-12T13:14:15Z
theDate = year + "-" + (month [1] ? month : "0" + month [0]) + "-" +
(dd[1] ? dd : "0" + dd[0]);
theTime = (hh[1] ? hh : "0" + hh[0]) + ":" + (mi[1] ? mi : "0" + mi[0]);
return [ theDate, theTime ].join("T");
}
</script>
I'm facing the same issue, my datepicker convert 14/07/2015 00:00 GMT(PARIS) to 13/07/2015 22:00 UTC.
I use this for a workaround as i only want to use the date and not time.
var dt = new Date($scope.END_DATE.value);
dt.setUTCHours(1); //set to utc 1 a.m.
$scope.holidays.END_DATE= dt;
The date is stored as 14/07/2015 01:00 in database.
Hope it helps
This is the conversion between utc to IST an vice versa
https://jsfiddle.net/wmhmgrjs/6/
//2016-08-02 12:55:19.743-- UTC <==> 2016-08-02 6:25:19.743 PM --IST
var date = new Date('8/02/2016 12:55:48 AM UTC'); //2016-07-29 07:02:40.323
var s=date.toString();
alert(s);
var d = new Date('8/02/2016 6:25:00 PM GMT+0530');
//var d = new Date("August 2, 2016 18:26:00");
var n = d.toUTCString();
alert(n);