Any suggestions on how to make my code cleaner and without code
duplication?As you can see there are a lot of repetitive declarations.
$scope.getStatistics = function(startDate, endDate) {
var start = startDate;
var date1 = start.getDate();
var month1 = (start.getMonth() +1);
var year1 = start.getFullYear();
var end = endDate;
var date2 = end.getDate();
var month2 = (end.getMonth() +1);
var year2 = end.getFullYear();
$http.get('/admin/api/stats?start=' + date1 + '-' + month1 + '-' + year1 + '&end=' + date2 + '-' + month2 + '-' + year2).success(function(data) {
$scope.stats = data;
});
}
$scope.getDiffPrev = function(startDate, endDate, computeDiff) {
var start = angular.copy(startDate)
start.setDate(start.getDate() - 7);
var date1 = start.getDate();
var month1 = start.getMonth() + 1;
var year1 = start.getFullYear();
var end = angular.copy(endDate)
end.setDate(end.getDate() - 7);
var date2 = end.getDate();
var month2 = end.getMonth() + 1;
var year2 = end.getFullYear();
$http.get('/admin/api/stats?start=' + date1 +'-'+ month1 +'-'+ year1 + '&end=' + date2 +'-'+ month2 +'-'+ year2 +'&computeDiff=true').success(function(data) {
$scope.stats = data;
});
}
function formatDate(date1){
var day1 = date1.getDate();
var month1 = (date1.getMonth() +1);
var year1 = date1.getFullYear();
return day1 + '-' + month1 + '-' + year1
}
$scope.getStatistics = function(startDate, endDate) {
$http.get('/admin/api/stats?start=' + formatDate(startDate) + '&end=' + formatDate(endDate)).success(function(data) {
$scope.stats = data;
});
}
$scope.getDiffPrev = function(startDate, endDate, computeDiff) {
var start = angular.copy(startDate)
start.setDate(start.getDate() - 7);
var end = angular.copy(endDate)
end.setDate(end.getDate() - 7);
$http.get('/admin/api/stats?start=' + formatDate(start) + '&end=' + formatDate(end) +'&computeDiff=true').success(function(data) {
$scope.stats = data;
});
}
You can created singleton service to avoid the code duplication, using this object you can access else where in your application.
For example you can use as foloows, I don't know exact code, but it will help you`.
angular.module('dateService', [ngResource])
.factory('DateService',['$http', function($http) {
var start, date1, month1, year1, end, date2, month2, result;
return {
date = function(startDate, endDate) {
start = startDate;
date1 = start.getDate();
month1 = (start.getMonth() +1);
year1 = start.getFullYear();
end = endDate;
date2 = end.getDate();
month2 = (end.getMonth() +1);
year2 = end.getFullYear();
$http.get('/admin/api/stats?start=' + date1 + '-' + month1 + '-' + year1 + '&end=' + date2 + '-' + month2 + '-' + year2).success(function(data) {
result = data;
});
return result;
}
}
}]);
angular.module('module-name', [dateService])
.cotroller('controller_name', ['DateService', function(dateService) {
$scope.getStatistics = function(startDate, endDate) {
var result = DateService.date(startDate, endDate);
result.then(function(data) {
$scope.start = data;
});
};
$scope.getDiffPrev = function(startDate, endDate, computeDiff) {
var result = DateService.date(startDate, endDate);
result.then(function(data) {
$scope.start = data;
});
};
}]);
Related
I am trying to apply the minimum and maximun for two dates inputs, namely:
<input type="date" name="proposal_from" id="proposal_from" />
<input type="date" name="proposal_to" id="proposal_to" />
<script type="text/javascript">
var proposal_from = document.getElementById("proposal_from");
var proposal_to = document.getElementById("proposal_to");
function setFromDate() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var minY = today.getFullYear();
var maxY = today.getFullYear() + 1;
var minimum = minY + '-' + mm + '-' + dd;
var maximum = maxY + '-' + mm + '-' + dd;
proposal_from.min = minimum;
proposal_from.max = maximum;
}
setFromDate();
proposal_from.addEventListener("change", function(){
var date = proposal_from.value.split("-");
var from_dd = date[2];
var from_mm = date[1];
var from_Y = date[0];
from_dd++;
var min_to_dd;
if(from_dd < 9){
min_to_dd = "0" + from_dd;
} else {
min_to_dd = from_dd;
}
var min_to_mm = from_mm;
var min_to_Y = from_Y;
from_Y++;
var max_to_dd;
if(from_dd < 9){
max_to_dd = "0" + from_dd;
} else {
max_to_dd = from_dd;
}
var max_to_mm = from_mm;
var max_to_Y = from_Y;
var minimum = min_to_Y + '-' + min_to_mm + '-' + min_to_dd;
var maximum = max_to_Y + '-' + max_to_mm + '-' + max_to_dd;
console.log(minimum);
console.log(maximum);
proposal_to.min = minimum;
proposal_to.max = maximum;
});
</script>
the event listener seems working now, the minimum and maximun dates get set as the date printed in the console should be and date values are completely correct. Before it was or example if I choose date 2021-10-04 I get minimum 2021-10-5 and 2022-10-5 instead of 2021-10-05 and 2022-10-05, is there anyway to do this with .padStart()?
You have to use the same logic that you used to pad zeros in setFromDate in your change event aswell.
Why this is needed?
You are performing incremental operation on from_dd using from_dd++ this will convert its type from String to Number. So convert it back to string again and perform you number padding logic.
function setFromDate() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var minY = today.getFullYear();
var maxY = today.getFullYear() + 1;
var minimum = minY + '-' + mm + '-' + dd;
var maximum = maxY + '-' + mm + '-' + dd;
console.log(minimum)
proposal_from.min = minimum;
proposal_from.max = maximum;
}
setFromDate();
proposal_from.addEventListener("change", function () {
var date = proposal_from.value.split("-");
var from_dd = date[2];
var from_mm = date[1];
var from_Y = date[0];
from_dd++;
var min_to_dd = String(from_dd).padStart(2, '0')
var min_to_mm = from_mm;
var min_to_Y = from_Y;
from_Y++;
var max_to_dd = String(from_dd).padStart(2, '0')
var max_to_mm = from_mm;
var max_to_Y = from_Y;
var minimum = min_to_Y + '-' + min_to_mm + '-' + min_to_dd;
var maximum = max_to_Y + '-' + max_to_mm + '-' + max_to_dd;
proposal_to.min = minimum;
proposal_to.max = maximum;
});
<input type="date" name="proposal_from" id="proposal_from" />
<input type="date" name="proposal_to" id="proposal_to" />
I am working on a small piece of code that looks to see if a value is equal to 'December 25 - January 9' and if it does increment the year (that I append to it) by one
However I can not figure out how to find that value. Every time I run the script it skips to the else part of the script when that value is selected.
Any guidance is appreciated
if ($('#date').val === 'December 25 - January 9') {
var startDates = $('#date').val().split(" - ");
var year = $('year').val;
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
}
else{
var startDates = $('#date').val().split(" - ");
var year = $('#year').val() ;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
console.log(myStartDates);
console.log(myEndDates);
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
Problem is you are using JQuery but chexking value as in javascript
$('#date')[0].value === 'December 25 - January 9'
or
$('#date').val() === 'December 25 - January 9'
should do it.
I see two places where you used val instead of val(), you want to call the function val not access a non-existent val field
if ($('#date').val() === 'December 25 - January 9') { // <-- val()
var startDates = $('#date').val().split(" - ");
var year = $('year').val(); // <-- val()
Try this. It should work.
You have var should be var() also year should be #year
if ($('#date').val() === 'December 25 - January 9') {
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
console.log(startDates);
console.log(year);
console.log(yearDec);
console.log(payPdStart);
console.log(payPdEnd);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
}
else{
var startDates = $('#date').val().split(" - ");
var year = $('#year').val() ;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
console.log(myStartDates);
console.log(myEndDates);
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + " </td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
I had this code on my page:
<script type="text/javascript">
var timeFinal = 3;
function timeZone(timeBegin,timeEnd) {
var tz = new Date();
tz = tz.getTimezoneOffset() / 60;
timeBegin = timeBegin - tz;
if (timeBegin <= -1) {
timeBegin = 24 - timeBegin;
}
else {
}
timeFinal = timeBegin + ":" timeEnd;
}
function FileModifDate() {
var dateModif = document.lastModified;
var startTimeModif = dateModif.indexOf(":") - 2;
var time = dateModif.substring(startTimeModif, dateModif.length - 3);
var timeBegin = time.substring(0, 1);
var timeEnd = time.substring(3, 4);
var date = dateModif.substring(0, 6);
date = date.substring(3, 4) + "/" + date.substring(0, 1) + "/" + date.substring(8, 9);
timeZone(timeBegin,timeEnd);
dateModif = timeFinal + " " + date;
document.getElementById('ModifDate').innerHTMl = dateModif;
}
</script>
But for some reason an error happens. It says Unexpected Identifier in the line 21:
timeFinal = timeBegin + ":" timeEnd;
Can someone tell me what is wrong?
timeFinal = timeBegin + ":" + timeEnd;
----------------------------------------------^ you missed + here
fixed the code here
I want to list all dates between 2 dates like..
list_dates('06/27/2013','07/31/2013');
This function will return all dates between 06/27/2013 - 07/31/2013 in array like..
['06/27/2013','06/28/2013','06/29/2013','06/30/2013','07/01/2013','...so_on..','07/31/2013'];
This function will work in all cases , Like older to newer , newer to older , or same dates like..
list_dates('06/27/2013','07/31/2013');
list_dates('07/31/2013','06/27/2013');
list_dates('07/31/2013','07/31/2013');
I do like...
function list_dates(a,b) {
var list = [];
var a_date = new Date(a);
var b_date = new Date(b);
if (a_date > b_date) {
} else if (a_date < b_date) {
} else {
list.push(a);
}
return list;
}
Demo : http://jsfiddle.net/fSGQ6/
But how to get dates between 2 dates ?
try this
list_dates('11/27/2013', '12/31/2013');
list_dates('03/21/2013', '02/14/2013');
list_dates('07/31/2013', '07/31/2013');
function list_dates(a, b) {
var list = [];
var a_date = new Date(a);
var b_date = new Date(b);
if (a_date > b_date) {
while (a_date >= b_date) {
var date_format = ('0' + (b_date.getMonth() + 1)).slice(-2) + '/' + ('0' + b_date.getDate()).slice(-2) + '/' + b_date.getFullYear();
list.push(date_format);
b_date = new Date(b_date.setDate(b_date.getDate() + 1));
}
} else if (a_date < b_date) {
while (b_date >= a_date) {
var date_format = ('0' + (a_date.getMonth() + 1)).slice(-2) + '/' + ('0' + a_date.getDate()).slice(-2) + '/' + a_date.getFullYear();
list.push(date_format);
a_date = new Date(a_date.setDate(a_date.getDate() + 1));
}
} else {
list.push(a);
}
console.log(list);
}
UPDATE: as poster requirement
var start = new Date(2013,06,27);
var end = new Date(2013,07,31);
var result =[];
var loop = true;
while(loop){
console.log(start.toISOString);
result.push(start);
start.setDate(start.getDate()+1)
if(start>end){
loop = false;
}
}
Date.prototype.getShortDate = function () {
// Do formatting of string here
return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
}
function list_dates(a, b) {
var a_date = new Date(a),
b_date = new Date(b),
list = [a_date.getShortDate()],
change = (a_date > b_date ? -1 : 1);
while (a_date.getTime() != b_date.getTime()) {
a_date.setDate(a_date.getDate() + change);
list.push(a_date.getShortDate());
}
return list;
}
How do I format a date in Javascript to something e.g. 'yyyy-MM-dd HH:mm:ss z'?
This date.toString('yyyy-MM-dd HH:mm:ss z'); never work out for me :/
Any idea?
======
I solved my own which I rewrote like this:
var parseDate = function(date) {
var m = /^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d) UTC$/.exec(date);
var tzOffset = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTimezoneOffset();
return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5] - tzOffset, +m[6]);
}
var formatDateTime = function(data) {
var utcDate = parseDate(data);
var theMonth = utcDate.getMonth() + 1;
var myMonth = ((theMonth < 10) ? "0" : "") + theMonth.toString();
var theDate = utcDate.getDate();
var myDate = ((theDate < 10) ? "0" : "") + theDate.toString();
var theHour = utcDate.getHours();
var myHour = ((theHour < 10) ? "0" : "") + theHour.toString();
var theMinute = utcDate.getMinutes();
var myMinute = ((theMinute < 10) ? "0" : "") + theMinute.toString();
var theSecond = utcDate.getSeconds();
mySecond = ((theSecond < 10) ? "0" : "") + theSecond.toString();
var theTimezone = new Date().toString();
var myTimezone = theTimezone.indexOf('(') > -1 ?
theTimezone.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join('') :
theTimezone.match(/[A-Z]{3,4}/)[0];
if (myTimezone == "GMT" && /(GMT\W*\d{4})/.test(theTimezone)) {
myTimezone = RegExp.$1;
}
if (myTimezone == "UTC" && /(UTC\W*\d{4})/.test(theTimezone)) {
myTimezone = RegExp.$1;
}
var dateString = utcDate.getFullYear() + "-" +
myMonth + "-" +
myDate + " " +
myHour + ":" +
myMinute + ":" +
mySecond + " " +
myTimezone;
return dateString;
}
and I get: 2012-11-15 22:08:08 MPST :) PERFECT!
function formatDate(dateObject) //pass date object
{
return (dateObject.getFullYear() + "-" + (dateObject.getMonth() + 1)) + "-" + dateObject.getDate() ;
}
Use this lib to make your life much easier:
var formattedDate = new Date().format('yyyy-MM-dd h:mm:ss');
document.getElementById("time").innerHTML= formattedDate;
DEMO
Basically, we have three methods and you have to combine the strings for yourself:
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
Example:
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year); </script>
for more details look at 10 steps to format date and time and also check this