Moment JS - Adds two days - javascript

Here is my current MomentJS code:
var date = moment($scope.dt);
for (var i = 0; i < parseInt($scope.numPagos); i++) {
$scope.resultados.push({
'numerodecuota' : i + 1,
'fechas' : date.add(1, 'days').format("MM/DD/YYYY"),
'pagos' : Math.round($scope.importeprestamo / $scope.numPagos + interes),
'interes' : Math.round(interes),
'capital' : $scope.importeprestamo / $scope.numPagos,
'fechaunix' : date.add(1, 'days').unix()
});
}// End for loop
And this is the result:
It has to be:
01/12/2017
01/13/2017
01/14/2017
01/15/2017
And so on.

Note: It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.
http://momentjs.com/docs/
Looks like you're adding 1 day, and then adding another day for the fechaunix date. Try just setting fechaunix to date once it's already been added:
$scope.resultados.push({
'numerodecuota' : i + 1,
'fechas' : date.add(1, 'days').format("MM/DD/YYYY"),
'pagos' : Math.round($scope.importeprestamo / $scope.numPagos + interes),
'interes' : Math.round(interes),
'capital' : $scope.importeprestamo / $scope.numPagos,
'fechaunix' : date.unix()
});

Because you are adding one day twice in your code
Once here
'fechas': date.add(1, 'days').format("MM/DD/YYYY"),
Again Here
'fechaunix': date.add(1, 'days').unix()
Add only once. see the example
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
var date = moment();
$scope.numPagos="5";
$scope.resultados=[];
for (var i = 0; i < parseInt($scope.numPagos); i++) {
$scope.resultados.push({
'numerodecuota': i + 1,
'fechas': date.add(1, 'days').format("MM/DD/YYYY"),
//'pagos': Math.round($scope.importeprestamo / $scope.numPagos + interes),
//'interes': Math.round(interes),
//'capital': $scope.importeprestamo / $scope.numPagos,
'fechaunix': date.unix()
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{resultados}}
</div>

Do you have two times method "date.add(1, 'days')";
try this:
var date = moment($scope.dt);
for (var i = 0; i < parseInt($scope.numPagos); i++) {
var current = date.add(1, 'days');
$scope.resultados.push({
'numerodecuota' : i + 1,
'fechas' : current.format("MM/DD/YYYY"),
'pagos' : Math.round($scope.importeprestamo / $scope.numPagos + interes),
'interes' : Math.round(interes),
'capital' : $scope.importeprestamo / $scope.numPagos,
'fechaunix' : current.unix()
});
}// End for loop

Related

Dynamic date Caluculation in Java script

I Am having two dataPickers of dijit/form/DateTextBox. One for startdate and another one for Enddate.
I want to check whether "Enddate > startdate+ 90days 3month)", if yes then I need to reset the end-date with startdate+ 90days.
format which am getting from DateTextBox 2018-04-25. Please help on this
var fromDate=digit.byId('startDate');
if(fromDate!=null) {
var fromtimestamp=new Date(digit.byId('startDate')).getTime();
var endtimestamp=new Date(digit.byId('endDate')).getTime();
var timestamp= new Date(digit.byId('startDate')).getTime+ (30 *24*60*60*1000);
if(endtimestamp>timestamp) {
// wants to reset with startdate+ 90days
}
}
You can achieve this but using dateBox min constaraint setting a change event in your start date , then set the digit.byId('endDate').constraints.min start date + 90
as :
digit.byId('startDate').on("change",function() {
var end = new Date(this.value);
end.setDate(end.getDate() + 90);
digit.byId('endDate').constraints.min = end;
})
See below programmatic snippet :
require(["dijit/form/DateTextBox", "dijit/form/Button","dojo/on" ,
"dojo/domReady!"
], function(DateTextBox,Button, On ) {
var startdate = new DateTextBox({
constraints:{
datePattern:'yyyy-MM-dd'
}
}, "startDate");
var enddate = new DateTextBox({
constraints:{
datePattern:'yyyy-MM-dd'
}
}, "endDate");
startdate.on("change",function() {
var end = new Date(this.value);
end.setDate(end.getDate() + 90);
enddate.constraints.max = end;
enddate.constraints.min = new Date(this.value);
})
});
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<body class="claro">
start :<div id="startDate" ></div>
end : <div id="endDate" ></div>
</body>

GoogleApp script. Google calendar script that display current day events

I have some questions regarding google calendar script that I'm building. So I managed to write the script and deploy it as a web app, but I encountered some problems:
1) It should list all current day events, but it lists only one event of the day
2) Also I want to display only the title of the event (it’s working now) and the start time and end time of the event. I managed to display a title (events[i].summary) and the start time of the event, but I was unable to display end time of the event and to change the format of the time that it would display time like this for example : 1pm – 2 pm.
3) Also what I want to do is to make the script run without pressing a button. I want it to work every time I open the published web app or refresh the web app page.
Here is the script code:
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp');
}
function listEvents() {
var actualDate = new Date();
var endOfDayDate = new
Date(actualDate.getFullYear(),actualDate.getMonth(),actualDate.getDate(),23,59,59);
var calendarId = 'primary';
var optionalArgs = {
timeMin: (new Date()).toISOString(),
timeMax: endOfDayDate.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: 'startTime'
};
var response = Calendar.Events.list(calendarId, optionalArgs);
var events = response.items;
var allEvents = [];
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
allEvents.push(events[i].summary + ' ' + events[i].start.dateTime);
}
return allEvents;
} else {
return ['No events found'];
}
And this is a HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Calendar App</h1>
<button onclick="listEvents()">List events</button>
<ul id='events'></ul>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(response){
var events = response;
for(var i = 0; i < events.length; i++) {
document.getElementById('events').innerHTML = '<li>' + response[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
</script>
</body>
</html>
This is the link to actual google scritp: Google Script
Thank you in advance for your help :)
Here is your modified (and working) code. You don't need to use advanced Calendar API since everything you need is available in CalendarApp, including a convenient getEventsForDay().
It shows all your events on opening as required.
code :
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp').setTitle('CalendarApp');
}
function listEvents() {
var today = new Date();
var cal = CalendarApp.getDefaultCalendar();
var events = cal.getEventsForDay(today);
var data = [];
data.push("Events for today "+Utilities.formatDate(today,Session.getScriptTimeZone(),"MMM dd yyyy"));
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
data.push(events[i].getTitle()+' : '+Utilities.formatDate(events[i].getStartTime(),Session.getScriptTimeZone(),"HH:mm")+' - '+Utilities.formatDate(events[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
}
return data;
} else {
return ['No events found','',''];
}
}
html & script :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style="font-family:arial,sans;font-size:12pt">
<h2>Calendar App</h2>
<div id="events">
</div>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(events){
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<p>' + events[0] + '</p>';
for(var i = 1; i < events.length; i++) {
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<li>' + events[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
window.onload = listEvents();
</script>
</body>
</html>
Here's a function I use to get my calendar events for the next 5 weeks. And I use it in conjunction with a webapp so it gets returned to a statement that looks like this document.getElementById('hotbox').innerHTML=hl; hotbox is just a div.
function getMyEvents()
{
var allCals=CalendarApp.getAllCalendars();
var s=Utilities.formatString('<strong>%s</strong>',Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"E MMM d, yyyy HHmm"))
var min=60 * 1000;
var hr=60 * min;
var day=24 * hr;
var wk=7 * day;
var start = new Date(new Date().setHours(0,0,0));
var end=new Date(start.valueOf() + (5 * wk));//you could make this + day instead of + (5 * wk)
var incl=['Calendar1Name','Calendar2Name'];//These are different calendar names as I have some special calendars for different functions
for(var i=0;i<allCals.length;i++)
{
if(incl.indexOf(allCals[i].getName())>-1)
{
s+=Utilities.formatString('<br /><strong>%s</strong>',allCals[i].getName());
var events=allCals[i].getEvents(start, end);
if(events)
{
s+='<br><ul>';
for(j=0;j<events.length;j++)
{
var calId=allCals[i].getId();
var evId=events[j].getId();
if(events[j].isAllDayEvent())
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s %s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),'All Day',Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d"),calId,evId);
}
else
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d, HHmm"),calId,evId);
}
}
s+='</ul>';
}
}
}
s+='<br /><input type="button" value="Delete Selected Events" onClick="delSelectedEvents();" style="width:250px;height:35px;text-align:center;margin:10px 0 10px 0;" />';
//var ui=HtmlService.createHtmlOutput(s);
//SpreadsheetApp.getUi().showModelessDialog(ui, 'My Events');
return s;
}

in angular js - how get current time on button click

I have two buttons like in and out, i need to show current time .. once clicked any button i need to send current time and date
<label>Today's Date : {{currentdate}}</label>
<label>Current Time : {{currenttime}}</label>
<button type="submit" class="btn" ng-disabled="disabledin" value="in" ng-
click="submitFun($event)">IN</button>
<button type="button" class="btn" ng-disabled="disabledout" value="out"
ng-click="submitFun($event)">OUT</button>
You are looking for something like this:
angular.module("myApp", [])
.controller("myCtrl", function($scope) {
$scope.someFunction = function() {
$scope.date = new Date();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<pre>current date: {{date | date: 'dd/MM/yyyy'}}</pre>
<pre>time: {{date | date: 'HH:mm:ss'}}</pre>
<button ng-click="someFunction()">show date time</button>
</body>
what about var time = new Date().
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
$scope.currentdate = today;
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
$scope.currenttime = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
In your controller you can use:
$scope.submitFun($event){
$scope.currentDate = new Date();
$scope.currentTime = new Date().getTime();
}
And you can change date format with filter in your html:
<label>Today's Date : {{currentdate | date:'yyyy-MM-dd HH:mm:ss Z'}}</label>
Read some DOC

Compare date and string with jquery

I'm trying to compare today date and the date from the string. They both has a string type. Why do I get "no!" ?
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" +(((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '16/10/2016';
if (String(datetodayvar) >= String(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
}
});
Turn them both to Date objects instead of strings.
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you have your "date string" from 3 different input fields(dropdowns or whatever) don't input a string, but make the date format as follows.
var year = 2015;
var month = 2-1; // February
var day = 27;
var now = new Date(year, month, day);
That way, you don't have to worry about date notation, localisation, if you need to use a - a . or / or something else inbetween.
Also remember the month, is always -1 because it starts counting as 0(januari being 0, december being 11.
Also, keep mind of day light savings time. That might go hayward with your freshly minted date objects too by subtracting an hour.
The snippet below has all the things i'd use in a "simple" comparing mechanism.
jQuery(document).ready(function () {
var str = '';
for(var c=1;c<32;c++) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#day').html(str);
var str = '';
for(var c=0;c<12;c++) {
str += '<option value="'+c+'">'+(c+1)+'</option>';
}
$('#month').html(str);
var str = '';
for(var c=parseInt(new Date().getFullYear());c>1990;c--) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#year').html(str);
$('#istodaycheck').on('click',function() {
var day = $('#day').get(0);
var month = $('#month').get(0);
var year = $('#year').get(0);
var date = new Date(
year.options[year.selectedIndex].value,
month.options[month.selectedIndex].value,
day.options[day.selectedIndex].value);
date.correctDst();
$('#output').text(date.isToday() ? 'yes' : 'no');
});
});
/**
* Retrieve standard timezome offset
*/
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
/**
* Checks if date is in day lights savings
*/
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
/**
* corrects the unwanted substraction of an hour on fresh dates.
*/
Date.prototype.correctDst = function() {
if(!this.dst()) {
this.setHours(this.getHours()+1);
}
}
/**
* Returns a date instance without time components.
*/
Date.prototype.justDate = function() {
var date = new Date(this.getFullYear(),this.getMonth(),this.getDate());
date.correctDst();
return date;
}
/**
* Tests if given date is today.
*/
Date.prototype.isToday = function() {
// strip possible time part.
var testdate = this.justDate();
var datetodayvar = new Date().justDate();
return datetodayvar.getTime() == testdate.getTime()
}
#output {
background-color: #eee;
border: 1px solid pink;
display: block;
width: 100%;
height:200px;
text-align: center;
font-size:121pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="day">
</select>
<select id="month">
</select>
<select id="year">
</select>
<button id="istodaycheck">Is this date today?</button>
<div id="output">
</div>
When comparing dates, always work with Date objects. The caveat with this is that when creating the objects, the provided date strings have to be in d/m/y or d-m-y format. Also note that today is not 16/10/2016.
jQuery(document).ready(function() {
var datetodayvar = new Date();
var deadlinadate = new Date('2/11/2016');
if (datetodayvar >= deadlinadate) {
console.log("yes!");
} else {
console.log("no!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First of all you are wrongly comparing two strings as if they were the numbers, when you do like this,
if(String(datetodayvar) >= String(deadlinadate)) { }
because if you want to compare strings you would have to
if(String(datetodayvar).equals(String(deadlinadate))){...
otherwise you compare the memory locations and not actual values.
Read more What is the difference between == vs equals() in Java?
This code will check whether the two string objects are greater than or equal to each other alphabetically, and not according to your actual requirement of date comparision. The functional code would be like this:
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
console.log("yes!");
} else {
console.log("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Assuming date format as dd/mm/yyyy and that deadline >= today
var ar = '02/11/2016'.split('/').map(Number);
var valid = new Date(ar[2],ar[1]-1,ar[0]) >= new Date().setHours(0,0,0,0);
console.log(valid);

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

Categories

Resources