add month to a date moment js - javascript

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"

Related

How to Set 2 different date in materialize datepicker using Javascript?

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>

Bootstrap Datepicker and Disable C#/JSON array of dates,

I have a list of dates that I want to disable in my bootstrap date picker. I cannot get the datesDisabled function to work with the array of dates returned from JSON. It does work with a hard coded array of dates.
Is there something that I need to do format the dates returned from JSON in order to get it to work?
Query:
var DatesBooked= JsonConvert.SerializeObject(db.Calendar.Where(x => x.CalLocation != "OFF")).Select(x => x.CalDate).Distinct().ToList());
In my view:
#Html.TextBox("AddedDates", null, new { #class = "form-control small", #Value = ViewBag.SelDate, autocomplete = "off" })
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.timepicker.js"></script>
<script src="~/Scripts/bootstrap-datepicker.min.js"></script>
<script>
var unavailableDates= #Html.Raw(Json.Encode(Model.DatesBooked));
$input = $("#AddedDates");
$input.datepicker({
multidate: true,
multidateSeparator: ',',
datesDisabled: unavailableDates,
});
</script>
unavailableDates value
var unavailableDates = "[\"2016-05-01T00:00:00\",\"2016-05-02T00:00:00\",\"2016-05-03T00:00:00\",\"2016-06-24T00:00:00\",\"2016-06-25T00:00:00\"]"
If I hardcode thisfor unavailableDates, everything works fine.
var unavailableDates = ["05/25/2016", "05/26/2016"]
How do I need to format the dates in order to get this to work?
TIA!
Well after many attempts and more research, I was able to solve this by doing the following:
I reformatted the date using C#:
var checkdates = db.Calendar.Where(x => x.CalLocation != "OFF")).Select(x => x.CalDate).Distinct().ToList()
var DatesBooked= JsonConvert.SerializeObject(checkdates, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "MM/dd/yyyy" });
Then in the view, I stripped the "\" characters returned by JSON and created an array:
var unavailableDates = #Html.Raw(Json.Encode(Model.DatesBooked));
var formatDates = unavailableDates.replace(/\\/g, "");
var trimDate = formatDates.slice(1, -1); // to remove " at beginning and end
var finalDates = JSON.parse("[" + trimDate + "]");
$input = $("#AddedDates");
$input.datepicker({
multidate: true,
multidateSeparator: ',',
datesDisabled: finalDates,
todayHighlight: true
});

Datepicker set default date

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

jQuery add 7 days to date (input and output type text)

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;
}

javascript calendar - highlight specific days

I have a datepicker javascript calendar that highlights specific holidays with a specific color.
I need it to highlight the days Wednsday (3) - Saturday (6) as well and am struggling.
Here is the code I am using thus far:
<script type="text/javascript">
$(document).ready(function() {
var SelectedDates = {};
SelectedDates[new Date('01/01/2014')] = new Date('01/01/2014');
SelectedDates[new Date('01/02/2014')] = new Date('01/02/2014');
SelectedDates[new Date('01/03/2014')] = new Date('01/03/2014');
$('#date1, #date2').datepicker({
beforeShowDay: function(date) {
var Highlight = SelectedDates[date];
if (Highlight) {
return [true, "highlighted", Highlight];
}
else {
return [true, '', ''];
}
}
});
});
</script>
The CSS looks like this:
.highlighted a{background:#f57d31 !important;}
And the form looks like this:
<input id="date1" name="date1" size="12" type="text" />
Please help on the best route to highlight Wednsday (3) - Saturday (6) on entire calendar.
Thanks~!
The following highlights Wednesday through Saturday for the months May through September:
$('#date1, #date2').datepicker({
beforeShowDay: function (date) {
var day = date.getDay();
var month = date.getMonth();
return [(day>=3 && day<=6)&&(month>=4 && month<=8), "highlighted"];
}
});
jsFiddle example

Categories

Resources