i am using Materialize template, I am trying to create 2 different default Date which is today and 2 days ago with javascript like this:
However, materialize only allow one default date using defaultDate using:
var elems = document.querySelectorAll('.datepicker');
var instances = M.Datepicker.init(elems, {defaultDate: new Date(),
setDefaultDate: true });
which set both dates to only one default date to
is there a way to set 2 different Default dates?
I found the way to do it, it's assigning them manually using their Input ID
// check current date
var d = new Date();
// recreate new date as mm/dd/yyyy to new date then subtract 2 in day
var dayBefore = new Date( (d.getMonth()+ 1) +"/" + (d.getDate()-2) + "/" + d.getFullYear());
// load datepicker class style from materialize
// and set default date for the cards
// getmonth() + 1 because the month start in 0 not 1
var elems = document.getElementById('FirstElement');
var instances = M.Datepicker.init(elems, {format: 'dd/mm/yyyy', defaultDate: dayBefore ,
setDefaultDate: true });
var elems = document.getElementById('SecondElement');
var instances = M.Datepicker.init(elems, {format: 'dd/mm/yyyy', defaultDate: d,
setDefaultDate: true });
And here's the HTML:
<input id="FirstElement" type="text" class="datepicker">
<label for="start_date">Start Date</label>
<input id="SecondElement" type="text" class="datepicker">
<label for="end_time">End Time</label>
Related
I am using Material Design and had to display the month and year only. So I used the month mode. But now when a user select a year and month, the whole date is visible for example if i had selected February 2019 from the datepicker, it would display that you selected 01/02/2019. Instead we want just Feb-2019.
This is my html md code
<md-input-container flex="100" layout="column">
<div style="font-size: 10px; color: blue;"
label ng-bind="::dateFields[2].label">
</div>
<md-datepicker ng-model="dateFields.selectedDate"
ng-required="dateFields.required"
md-date-locale="dateFields.locale"
md-mode="month"
md-open-on-focus="true">
</md-datepicker>
What shall i edit in order to just get the month and year after selection?
you can make use of moment js for formatting date as you wanted,
var monthFormat = buildLocaleProvider("MMM-YYYY");
var ymdFormat = buildLocaleProvider("YYYY-MM-DD");
function buildLocaleProvider(formatString) {
return {
formatDate: function(date) {
if (date) return moment(date).format(formatString);
else return null;
},
parseDate: function(dateString) {
if (dateString) {
var m = moment(dateString, formatString, true);
return m.isValid() ? m.toDate() : new Date(NaN);
} else return null;
}
};
}
$scope.dateFields = {
......
locale: monthFormat
};
Look into this demo https://plnkr.co/edit/eV2Kmt.
Reference answer - Angular-Material set a Datepicker with only months and years
I am trying to add no of months to a given date using js. fd_start_date has the start date, but moment.js returns "Invalid Date". I am using date picker to select date in format YYYY-MM-DD.
$('#fd_start_date').click(function () {
var start_date=$("#fd_start_date").val();
var no_of_months=$("#fd_duration").val();
var currentDate = moment(start_date);
var future_date = moment(currentDate).add(no_of_months, 'months');
console.log(future_date);
});
Works for me if I change to on input and have a value in the month field
$('#fd_start_date, #fd_duration').on("input",function() {
var start_date = $("#fd_start_date").val();
if (start_date) {
var no_of_months = $("#fd_duration").val();
var currentDate = moment(start_date);
var future_date = moment(currentDate).add(no_of_months, 'months');
console.log(future_date);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input type="date" id="fd_start_date" /><input type="number" id="fd_duration" value="1" />
You can achieve this in the following way:
// Getting the current moment
const currentTime = moment()
// Adding a month to it
const futureMonth = currentTime.add(1, 'M');
console.log(futureMonth)
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
I am using this in my project and this logic is working fine for me.
$scope.o.DateOfBirth = "31/03/2021";
var currentDate =moment($scope.o.DateOfBirth, 'DD/MM/YYYY').format('YYYY-MM-DD');
var futureMonth = moment(currentDate ).add(24, 'month').format("YYYY-MM-DD");
console.log(currentDate.format('DD-MM-YYYY'));
console.log(futureMonth.format('DD-MM-YYYY'));
output : "2023-03-31"
I am trying to set default date for Jquery datepicker on init. Here is my html:
var content = "";
content = "<table class=\"filter-table\">";
content += "<tr><td><label for='startDate'>From </label></td><td><input name='startDate' id='startDate' class='date-picker' /></td></tr>";
content += "<tr><td> </td></tr>";
content += "<tr><td><label for='endDate'>To </label></td><td><input name='endDate' id='endDate' class='date-picker' /></td></tr>";
And my JavaScript:
<script type="text/javascript">
function showdatepicker() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
changeDay: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd',
onClose: function(dateText, inst) {
var day = $("#ui-datepicker-div .ui-datepicker-day :selected").val();
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$('#startDate').datepicker({defaultDate: -30});
$('#endDate').datepicker({defaultDate: new Date()});
}
});
}
</script>
What I am trying to do is set the date and show in the textbox when on load the page. The endDate should be current date whilst start date should be one month before. However, by using these codes, it does not display the date in textbox when first load.
I wonder why is it so. Thanks in advance.
I, like you, could not use a method on the datepicker to populate a default date in the input.
So instead, I made code using vanilla JS to calculate the default dates and format them to display in the textboxes.
Here is the JS I added:
function showdatepicker() {
// same as yours
}
function populateDefaultValues() {
var today = new Date();
var month = today.getMonth() - 1,
year = today.getFullYear();
if (month < 0) {
month = 11;
year -= 1;
}
var oneMonthAgo = new Date(year, month, today.getDate());
$('#startDate').val($.datepicker.formatDate('yy-mm-dd', today));
$('#endDate').val($.datepicker.formatDate('yy-mm-dd', oneMonthAgo));
}
$(function() {
populateDefaultValues();
showdatepicker();
});
jsFiddle
Have a look at the defaultDate option. It provides exactly the features you need.
Because the default date options will vary for each datepicker you will need to initialise them separately (basically copy-paste, and tweak to suit).
http://api.jqueryui.com/datepicker/#option-defaultDate
I am trying to do a simple page that takes a date (input type TEXT), and once the date is entered, another field will add 7 days to the input and display the date (+7 days) in a text input. My knowledge of jQuery is limited so I may have a small bug...
<html>
<head>
<title>Date Plus 7 Days</title>
<script type="text/javascript">
$(document).ready(function(){
function DateFromString(str){
str = str.split(/\D+/);
str = new Date(str[2],str[0]-1,(parseInt(str[1])+7));
return MMDDYYYY(str);
}
function MMDDYYYY(str) {
var ndateArr = str.toString().split(' ');
var Months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec';
return (parseInt(Months.indexOf(ndateArr[1])/4)+1)+'/'+ndateArr[2]+'/'+ndateArr[3];
}
function Add7Days() {
var date = $('#start_date').val();
var ndate = DateFromString(date);
return ndate;
}
$('#start_date').change(function(){
$('#end_date') = Add7Days();
})
});
</script>
</head>
<body>
Start Date
<input type="text" id="start_date" value=''>
<br>
End date
<input type="text" id="end_date" value=''>
</body>
</html>
What did I do wrong?
Thanks!
you've attempted to assign an object to $('#end_date'). jQuery deals with this in a different way by altering the value of the input box by leveraging .val('value-here')
Try this:
$('#start_date').change(function(){
$('#end_date').val(Add7Days());
});
See this fiddle: http://jsfiddle.net/zydZ2/
Also, Moment.JS is great for parsing and manipulating dates, I'd strongly recommend checking that out: http://momentjs.com/
Hope this helps!
functionally to add 7days to an existing date can be achieved by using
var today_date = new Date()
alert(today_date)
today_date.setDate(today_date.getDate() + 7)
alert(today_date)
this will add seven days to an existing date if its 31 than it will make it 7th of next month
hope this help
Your may using JQuery & JqueryUI datepicker featured to did it.
$('#start_date').datepicker({
dateFormat: 'mm/dd/yy',
minDate: 0,
});
$("#end_date").datepicker({
dateFormat: 'mm/dd/yy',
minDate: 7,
});
var _dt = new Date();
var _dt = _dt.setDate(_dt.getDate());
$("#start_date").datepicker("setDate","mm/dd/yy", _dt);
$("#end_date").datepicker("setDate", "mm/dd/yy", _dt);
you may refer this http://jsfiddle.net/o9grLdf0/12/
min = 0 for input startdate = today date
and
min = 7 mean today + 7 day for enddate
function listDatesBetweenTwoDates(S_dateA, S_dateB) {
var O_dateA = moment(S_dateA).add(1, 'd');
var O_dateB = moment(S_dateB).add(1, 'd');
var O_itr = moment.twix(O_dateA, O_dateB).iterate("days");
var A_range = [];
while (O_itr.hasNext()) {
A_range.push(O_itr.next().toDate())
}
return A_range;
}
I need to use datepicker which provides me the option of restricting the selectable dates. We had been using jQuery UI which is used to support it using minDate, maxDate options.
$("#id_date").datepicker({minDate: +1, maxDate: '+1M +10D'});
Recently we started using Twitter Bootstrap for our styles. And apparently, Twitter Bootstrap is incompatible with jQuery UI styles. So I tried using one of the bootstrap compatible datepickers available at http://www.eyecon.ro/bootstrap-datepicker/.
Unfortunately, the above plugin is not as configurable as jQuery UI's datepicker. Can anyone help me out with restricting the selectable date ranges in the new datepicker.
The Bootstrap datepicker is able to set date-range. But it is not available in the initial release/Master Branch. Check the branch as 'range' there (or just see at https://github.com/eternicode/bootstrap-datepicker), you can do it simply with startDate and endDate.
Example:
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:
http://bootply.com/74352
JS file:
var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();
ToEndDate.setDate(ToEndDate.getDate()+365);
$('.from_date').datepicker({
weekStart: 1,
startDate: '01/01/2012',
endDate: FromEndDate,
autoclose: true
})
.on('changeDate', function(selected){
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
$('.to_date').datepicker('setStartDate', startDate);
});
$('.to_date')
.datepicker({
weekStart: 1,
startDate: startDate,
endDate: ToEndDate,
autoclose: true
})
.on('changeDate', function(selected){
FromEndDate = new Date(selected.date.valueOf());
FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
$('.from_date').datepicker('setEndDate', FromEndDate);
});
HTML:
<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text"
And do not forget to include bootstrap datepicker.js and .css files aswell.
The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:
JS file:
$(".from_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var startDate = new Date(selected.date.valueOf());
$('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
$('.to_date').datepicker('setStartDate', null);
});
$(".to_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var endDate = new Date(selected.date.valueOf());
$('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
$('.from_date').datepicker('setEndDate', null);
});
HTML:
<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">
Most answers and explanations are not to explain what is a valid string of endDate or startDate.
Danny gave us two useful example.
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
But why?let's take a look at the source code at bootstrap-datetimepicker.js.
There are some code begin line 1343 tell us how does it work.
if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([-+]\d+)([dmwy])/,
parts = date.match(/([-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
}
There are four kinds of expressions.
w means week
m means month
y means year
d means day
Look at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$.
You can do more than these -0d or +1m.
Try harder like startDate:'+1y,-2m,+0d,-1w'.And the separator , could be one of [\f\n\r\t\v,]
Another possibility is to use the options with data attributes, like this(minimum date 1 week before):
<input class='datepicker' data-date-start-date="-1w">
More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html
i am using v3.1.3 and i had to use data('DateTimePicker') like this
var fromE = $( "#" + fromInput );
var toE = $( "#" + toInput );
$('.form-datepicker').datetimepicker(dtOpts);
$('.form-datepicker').on('change', function(e){
var isTo = $(this).attr('name') === 'to';
$( "#" + ( isTo ? fromInput : toInput ) )
.data('DateTimePicker')[ isTo ? 'setMaxDate' : 'setMinDate' ](moment($(this).val(), 'DD/MM/YYYY'))
});
<script type="text/javascript">
$(document).ready( function() {
$("#submitdate").datepicker( {
minDate: 0,
maxDate: 0,
dateFormat: "yy-mm-dd",
});