I am working on some calculation what i get is no of months, so i need to add to the startdate and display end date dynamically upon added months.
My effort so far :
View Model:
function calculation() {
var self = this;
self.months= ko.observable("");
self.StartDate = ko.observable(""); // On my get i get startdate like **2014-06-24**
self.EndDate = ko.computed(function () {
return self.StartDate() + ?? // i have no clue how to add
});
My cshtml code:
<input type="text" data-bind="value:$data.StartDate" />
<input type="text" data-bind="value:$data.EndDate" />
EDIT :
Fallowing suggestions i tried like this but formatting is not up to mark sadly
self.EndDate = ko.computed(function () {
var date = new Date(self.StartDate());
date.setMonth(date.getMonth() + 8); // tried static
return date.toLocaleDateString() ;
});
I am getting something like 24 February 2015 but i expect to be 2015-02-24 as i passed date in same format
Any suggestions are appreciated
You will have to take in to account the various edge cases that come with dates. For example, the 31st October + 1 month is obviously not the 31st November. And then you have to take in to account that the number of days in February varies depending on whether or not it is a leap year.
Look at the answer from Jazaret in this question to figure out exactly what the date is in x months from now:
How to add months to a date in JavaScript?
Then you can add this to your code:
self.EndDate = ko.computed(function () {
var date = new Date(self.StartDate());
return date.addMonths(5); // add however months you want
});
Adding months (like adding one month to January 31st) can overflow the days field and cause the month to increment (in this case you get a date in March). If you want to add months and then overflow the date then .setMonth(base_date.getMonth()+monthsToAdd) works but that's rarely what people think of when they talk about incrementing months.
I use this to add months to a date when I don't want to overflow the month:
function addMonthsNoOverflow(dateParam, intParam) {
var sum = new Date(new Date(dateParam.getTime()).setMonth(dateParam.getMonth() + intParam);
if (sum.getDate() < dateParam.getDate()) { sum.setDate(0); }
return(sum);
}
Notes:
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.
http://jsfiddle.net/zjdj3zxz/1/
Here's a fairly basic example of adding months to a date:
JSFiddle
Fiddle Code:
var ViewModel = function () {
var self = this;
self.StartDate = ko.observable(new Date("2014-06-24"));
self.EndDate = ko.computed(function () {
var myDate = new Date(self.StartDate());
myDate.setMonth(myDate.getMonth() + 5)
return myDate;
});
};
$(function () {
var vm = new ViewModel();
ko.applyBindings(vm);
});
As #AndrewC states in his post, this doesn't cover edge cases and you will have to account for months with different numbers of days in them and handle them according to your requirements.
EDIT: Please include the Moment.js library in your project. This way the date calculation and formatting will be very easy. Just take a look at the examples in the docs.
So, I believe that is what you want:
http://jsfiddle.net/
var ViewModel = function(date, noOfMonths) {
this.calculation = ko.computed(function(){
var m = moment(date);
return m.add('months',noOfMonths).format('YYYY-MM-DD');
},this);
};
ko.applyBindings(new ViewModel(new Date('7/31/2014 17:15:00'), 4));
Related
I used "moment" in my project.
I tried to get whole weeks starting date of the given year.
var weeksOfYear = moment("2018").weeks();
But it won't works.
I want following output.
[1,8,15,22,29,5,12,19,26,5,12,19,26,2,9,16,23,30,7,14,21,28,4,11,18,25,2,9,16,23,30,6,13,20,27,3,10,17,14,1,8,15,22,29,5,12,19,26,3,10,17,24];
if you compare above array with calendar then you will see that these are the starting date of the week of 2018.
Please tell me, how can i achieve it?
This works. Though I am sure that someone else will have a neater answer.
var yearInQuestion = 2018;
var setYear = moment().set('year', yearInQuestion);
var firstMonday = (setYear.startOf('year')).startOf('isoweek');
// NB - Monday of that week might have been in the previous year
if (firstMonday.year() < yearInQuestion) {
firstMonday.add(7, 'days');
}
var datesArray = [];
while (firstMonday.year() === yearInQuestion) {
datesArray.push(firstMonday.date());
firstMonday.add(7, 'days');
}
console.log(datesArray);
I am trying to calculate the days between 2 dates and it is working as far as I can tell but I keep getting stupidly high numbers which clearly isn't right, I have a feeling this is the way my dates are set out. my dates are set out as dd/mm/yyyy and this is the code I am using:
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
This is the question I used to get the answer:
JavaScript date difference Days
When it writes to the console this is the result I get:
diff=>17301.95833332176
I have had a play with the code, although I have not used HTML, i set the vars statically below.
var end_date = new Date("May 25, 2017");
var start_date = new Date("May 23, 2017");
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I have also checked it with a 3 value date format
var end_date = new Date(2017,4,25);
var start_date = new Date(2017,4,23);
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I manage to get an output of 2. Which is what i expected. The code you supplied looks ok to me. Maybe look at the HTML to check that the values being passed are in the correct format.
Jquery datepicker may be of help to you here.
You could also use moment: https://momentjs.com
var moment = require('moment');
var start_moment = moment(start_date);
var end_moment = moment(end_date);
var days = start_moment.diff(end_moment, 'days');
console.log("diff=>" + days);
You can also get weeks, months etc. with this method
Easy solution, is to use countBtw
var { date } = require('aleppo')
//..
date.countBtw('all', date1, date2)
I'm generating a dynamic transaction data table in my app. In this table every month sould be seperated and a total row should be added after the month.
My version worked until the year changed. December 2016 and January 2017 are not getting seperated because the comparison isn't made correct.
Simplified I'm doing the following:
var dateNow = moment("2016-12-21T13:14:55").format("MM-YYYY");
var lastDate = moment("2017-01-13T14:23:12").format("MM-YYYY");
if(lastDate > dateNow) // This is false
{
// This isn't executed
}
Why is the comparison false? It works for all other months.
The moment.js version I'm using is 2.7.0.
Try like this,
var before = "12-2016";
var after = "01-2017"
var beforeInMoment = moment.utc(before, "MM-YYYY");
var afterInMoment = moment.utc(after, "MM-YYYY");
if(beforeInMoment.isBefore(afterInMoment)){
console.log('Yes');
}
What a day I've been having... anyway, I have been assisting some colleagues with an AngularJS project and so much is wrong, anyway... I am using the AngularJS UI Bootstrap Datepicker version 0.11.2 with AngularJS version 1.3. So far so good however I wish to set the minimum date 2 months from the current day, the maximum date six months from the current day and the initial date 2 months from the current day. This is what I have so far:
View
<div data-datepicker
data-ng-model="dt"
data-min-date="minDate"
data-max-date="maxDate"
data-max-mode="day"
data-show-weeks="false"
data-starting-day="1"
data-year-range="2"
class="custom-date-picker"></div>
and in my controller...
var today = new Date(),
twoMonth = today.setMonth(today.getMonth() + 2),
sixMonth = today.setMonth(today.getMonth() + 6);
$scope.today = function() {
$scope.minDate = twoMonth;
$scope.maxDate = sixMonth;
};
$scope.today();
This is all find however I've noticed that minDate is correct, maxDate is actually 8 months in the future and when I add the following to the directive to set the initial date like so (notice data-init-date="minDate")
<div data-datepicker
data-ng-model="dt"
data-init-date="minDate"
data-min-date="minDate"
data-max-date="maxDate"
data-max-mode="day"
data-show-weeks="false"
data-starting-day="1"
data-year-range="2"
class="custom-date-picker"></div>
I get the following error!
TypeError: undefined is not a function
at e._refreshView (js/vendor/angular/ng-ui-bootstrap-tpls-0.11.2.min.js:8:16705)
at refreshView (js/vendor/angular/ng-ui-bootstrap-tpls-0.11.2.min.js:8:13968)
at link (js/vendor/angular/ng-ui-bootstrap-tpls-0.11.2.min.js:8:17848)
at B (js/vendor/angular/angular-1.3.0-beta.18.min.js:55:369)
at js/vendor/angular/angular-1.3.0-beta.18.min.js:62:378
at g (js/vendor/angular/angular-1.3.0-beta.18.min.js:48:105)
at js/vendor/angular/angular-1.3.0-beta.18.min.js:47:233
at js/vendor/angular/angular-1.3.0-beta.18.min.js:49:54
at Object.r [as transclude] (js/vendor/angular/angular-1.3.0-beta.18.min.js:52:497)
at js/vendor/angular/angular-1.3.0-beta.18.min.js:215:316 <table role="grid" aria-labelledby="{{uniqueId}}-title" aria-activedescendant="{{activeDateId}}" ng-switch-when="day" tabindex="0">
Does anyone know where I am going wrong?
It is important to note that your Date gets mutated here:
var today = new Date(),
twoMonth = today.setMonth(today.getMonth() + 2),
sixMonth = today.setMonth(today.getMonth() + 6);
Each setMonth adjusts the original Date. Hence the eight month issue.
The latter issue is caused by the fact that twoMonth and sixMonth are numbers. I think your directive expects Dates instead so wrap them with new Date(...).
Solution
I think something like this should work:
var twoMonth = offsetMonths(2);
var sixMonth = offsetMonths(6);
function offsetMonths(offset) {
var ret = new Date();
ret.setMonth(ret.getMonth() + offset);
return new Date(ret);
}
Of course you can simplify things a lot by using something like moment.js.
How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.
If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”.
if (txtDate && txtDate.value == "")
{
txtDate.focus();
alert("Please enter a date in the 'Date' field.")
return false;
}
Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:
var myDate = new Date(yearno, monthno-1, dayno);
//you could put hour, minute, second and milliseconds in this too
Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)
Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:
//today (right now !-) can be constructed by an empty constructor
var today = new Date();
var olddate = new Date(2008,9,2);
var diff = today.getTime() - olddate.getTime();
var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds
alert(diffInDays);
This will return a decimal number, so probably you'll want to look at the integer-value:
alert(Math.floor(diffInDays));
To get the date difference in days in plain JavaScript, you can do it like this:
var billeddate = Date.parse("2008/10/27");
var getdate = Date.parse("2008/09/25");
var differenceInDays = (billeddate - getdate)/(1000*60*60*24)
However if you want to get more control in your date manipulation I suggest you to use a date library, I like DateJS, it's really good to parse and manipulate dates in many formats, and it's really syntactic sugar:
// What date is next thrusday?
Date.today().next().thursday();
//or
Date.parse('next thursday');
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
You can use this to check for valid date
function IsDate(testValue) {
var returnValue = false;
var testDate;
try {
testDate = new Date(testValue);
if (!isNaN(testDate)) {
returnValue = true;
}
else {
returnValue = false;
}
}
catch (e) {
returnValue = false;
}
return returnValue;
}
And this is how you can manipulate JS dates. You basically create a date object of now (getDate), add 31 days and compare it to the date entered
function IsMoreThan31Days(dateToTest) {
if(IsDate(futureDate)) {
var futureDateObj = new Date();
var enteredDateObj = new Date(dateToTest);
futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now.
//adds hours and minutes to dateToTest so that the test for 31 days is more accurate.
enteredDateObj.setHours(futureDateObj.getHours());
enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1);
if(enteredDateObj >= futureDateObj) {
return true;
}
else {
return false;
}
}
}
Hello and good day for everyone
You can try Refular Expressions to parse and validate a date format
here is an URL yoy can watch some samples and how to use
http://www.javascriptkit.com/jsref/regexp.shtml
A very very simple pattern would be: \d{2}/\d{2}/\d{4}
for MM/dd/yyyy or dd/MM/yyyy
With no more....
bye bye