Diffrence between two datetime in desire format using angular js - angularjs

How to check diffrence between two datetime in desire format using angular js.
var ms = moment($scope.date1,"yyyy-MM-dd HH:mm:ss").diff(moment($scope.date2,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Date diff.........",s);
output:
date1........ 2017-12-26 16:20:00
date2........ 2017-12-26 15:10:38
Diff- 01:10
(If should ignore date because there is not date diffrence and if date diffrence is there then it show display like 03:10:05)
Diff (In format- DD-HH-MM)
DD-Days
HH-Hours
MM-Minutes
Tried Code:
$scope.cdate = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
console.log("current time........",$scope.cdate);
$scope.Mydata=Data.timestamp; //I am Getting this data from response
this.getDateDiff = function(cdate, Mydata) {
let d1 = new Date($scope.cdate);
let d2 = new Date($scope.Mydata);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.cdate, $scope.Mydata);
console.log("days diff.........",$scope.dateDiff);
Output:
Input:
current time- 2017-12-29 10:19:41
Mydata- 2017-02-09 18:16:38
result is coming wrong-
{days: "23", hours: "16", minutes: "03", seconds: "03"}

You can achieve it by using native JavaScript.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38"
this.getDateDiff = function(date1, date2) {
let d1 = new Date(date1);
let d2 = new Date(date2);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.date1, $scope.date2);
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
</head>
<body ng-controller="MainCtrl">
<div>date1...... {{date1}}</div>
<div>date2...... {{date2}}</div>
<div>
<span>Diff - </span>
<span ng-if="dateDiff.days > 0">{{dateDiff.days}} : </span>
<span>{{ dateDiff.hours }} : </span>
<span>{{ dateDiff.minutes }}</span>
</div>
</body>
</html>

See if this works for you.
your controller file-
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38";
var diff = moment.utc(date1, "yyyy-MM-DD HH:mm:ss").diff(moment.utc(date2, "yyyy-MM-DD HH:mm:ss"), 'minutes');
var days=diff/(24*60);
var hours=diff/60;
var minutes=diff%60;
$scope.arr = [];
if(parseInt(days)){
arr.push(parseInt(days));
}
if(parseInt(hours)){
arr.push(('0'+hours).substring(-1, 2));
}
if(minutes){
arr.push(('0'+minutes).substring(-1, 2));
}
console.log(arr.join(':'));
Your html file-
...
<div>{{arr.join(':')}}</div>
...

Related

Year value is not showing in angularjs

I'm trying to show the value of year in the view that is HTML, but year values are not showing at all. Although, My other value is showing while the condition is not acivated (like credit card), but when I activate it, year values is not showing, while values are coming from the controller and is shown in the console.
Here is the view code :-
<div class="col-xs-2 innerN" style="width: 14%;">
<select ng-disabled="page.creditcard.isDisabled" class="form-control innerN" placeholder="YYYY" name="ccExpYear" ng-model="page.expyear" required style="border-left:none">
<option value="XX" selected ng-if="page.creditcard.isDisabled">XX</option>
<option ng-repeat="year in page.yearList" value="{{year}}" ng-if="!page.creditcard.isDisabled">{{year}}</option>
</select>
</div>
And Here is the controller code :-
$scope.page.monthList = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", ];
$scope.page.yearList = [];
var d = new Date();
var year = d.getFullYear();
//$scope.page.yearList.push(year);
$scope.page.expyear = year;
console.log("Pawan2", $scope.page.expyear);
for (var i = 0; i < 21; i++) {
{
$scope.page.yearList.push(year + i);
};
}
$scope.years = $scope.page.yearList;
console.log("YearListPawan", $scope.page.yearList);
$scope.page.expmonth = "01";
$scope.monthList = "01";
// watcher
$scope.$watchGroup(['page.expmonth', 'page.expyear'], function(newValues, oldValues, scope) {
//MM-YYYY
if (typeof newValues[1] == "undefined" || typeof newValues[0] == "undefined") scope.authorize.creditCard
.expirationDate = null;
else $scope.authorize.creditCard.expirationDate = newValues[1] + "-" + newValues[0];
console.log("Pawan", $scope.authorize.creditCard.expirationDate)
}, true);
I hope, I'm clear anough to get the answer for this.
PS : THnx in advance for help.
You should use ng-value instead of value:-
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.page = {};
$scope.page.monthList = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", ];
$scope.page.yearList = [];
var d = new Date();
var year = d.getFullYear();
//$scope.page.yearList.push(year);
$scope.page.expyear = year;
console.log("Pawan2", $scope.page.expyear);
for (var i = 0; i < 21; i++) {
{
$scope.page.yearList.push(year + i);
};
}
$scope.years = $scope.page.yearList;
$scope.authorize = {creditCard: {expirationDate: 'date'}};
console.log("YearListPawan", $scope.page.yearList);
$scope.page.expmonth = "01";
$scope.monthList = "01";
// watcher
$scope.$watchGroup(['page.expmonth', 'page.expyear'], function(newValues, oldValues, scope) {
//MM-YYYY
if (typeof newValues[1] == "undefined" || typeof newValues[0] == "undefined")
$scope.authorize.creditCard.expirationDate = null;
else
$scope.authorize.creditCard.expirationDate = newValues[1] + "-" + newValues[0];
console.log("Pawan", $scope.authorize.creditCard.expirationDate)
}, true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-xs-2 innerN" style="width: 14%;">
<select ng-disabled="page.creditcard.isDisabled" class="form-control innerN" placeholder="YYYY" name="ccExpYear" ng-model="page.expyear" required style="border-left:none">
<option value="XX" selected ng-if="page.creditcard.isDisabled">XX</option>
<option ng-repeat="year in page.yearList" ng-value="year" ng-if="!page.creditcard.isDisabled">{{year}}</option>
</select>
</div>
</div>
Here is the solution that I have applied to the scenario -
And here is the controller code with few changes : -
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.page = {};
$scope.page.monthList = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", ];
$scope.page.yearList = [];
var d = new Date();
var year = d.getFullYear();
var addYears = function () {
var d = new Date();
var year = d.getFullYear();
$scope.page.yearList = [];
var i = 0;
for (i = 0; i < 40; i++) {
$scope.page.yearList.push(year.toString());
year++;
}
}
addYears();
$scope.years = $scope.page.yearList;
$scope.page.expyear = d.getFullYear();
$scope.page.expmonth = "01";
$scope.monthList = "01";
// watcher
$scope.$watchGroup(['page.expmonth', 'page.expyear'], function(newValues, oldValues, scope) {
//MM-YYYY
if(typeof newValues[1] == "undefined" || typeof newValues[0] == "undefined")
scope.authorize.creditCard.expirationDate = null;
else
$scope.authorize.creditCard.expirationDate = newValues[1] + "-" + newValues[0];
console.log("Pawan", $scope.authorize.creditCard.expirationDate)
}, true);
Here is the view code :-
<!DOCTYPE html>
<html><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div class="col-xs-2 innerN" style="width: 14%;">
<select ng-disabled="page.creditcard.isDisabled" class="form-control innerN" placeholder="YYYY" name="ccExpYear" ng-model="page.expyear" required style="border-left:none">
<option value="XX" selected ng-if="page.creditcard.isDisabled">XX</option>
<option ng-repeat="year in page.yearList" value="{{year}}" ng-if="!page.creditcard.isDisabled">{{year}}</option>
</select>
</div>
Hope, this will help to others.

Error in calculating distance traveld by user

I'm a fresher for ionic and angularjs, I'm developing a tracking app, in which I am not able to calculate the tracked distance and store it in database.
here is my index.html
<!DOCTYPE html>
<html ng-app="starter">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link rel="manifest" href="manifest.json">
<link href="css/ionic.app.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAHe3efHByU2G1ECBpenC8ZpiXlpO7GFXA "></script>
</head>
<body ng-controller="MapCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Maps</h1>
</ion-header-bar>
<ion-content ng-init="first(User)">
<div class="padding">
<button class="button button-large button-calm" ng-click="starttrack(User)">Start</button>
<button class="button button-large button-assertive" ng-click="endtrack(User)">End</button>
</div>
<div>coordinates = {{getText(User)}}</div>
<button class="button button-small button-balanced" ng-click="dist()">Show distance</button>
</ion-content>
</ion-pane>
</body>
</html>
here is my app.js
.factory('AllServices', function($http) {
return {
drivertrackFunction: function(User) {
var data = { coordinates: User.coordinates,
dis: User.dis};
var link = 'http://localhost/track.php';
return $http.post(link,data);
}
};
})
.controller('MapCtrl', function($scope, filterFilter, $state, $cordovaGeolocation, $interval, AllServices) {
$scope.User = {};
$scope.User.mysrclat= 0;
$scope.User.mysrclong = 0;
$scope.User.timer = "";
$scope.addstring=[];
$scope.addstring1 = [];
$scope.User.string1="";
$scope.User.coordinates=undefined;
$scope.User.string3="";
$scope.lat1 = "";
$scope.lon1 = "";
$scope.lat2 = "";
$scope.lon2 = "";
$scope.User.d = "";
$scope.User.totalDis="";
$scope.originals = [];
$scope.User.temp = 0;
$scope.points = "";
$scope.User.pLen = "";
$scope.User.len = "";
$scope.User.origin1 = "";
$scope.User.destinationB = "";
$scope.User.geocoder = "";
$scope.User.service = "";
$scope.User.originList ="";
$scope.User.destinationList = "";
$scope.User.outputDiv = "";
$scope.User.TotDis = "";
$scope.User.TotDur = "";
$scope.User.dis = 0;
$scope.first = function(User) {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
$scope.User.mysrclat = position.coords.latitude;
$scope.User.mysrclong = position.coords.longitude;
$scope.User.string1 = $scope.User.mysrclat + "," + $scope.User.mysrclong;
console.log($scope.User.mysrclat);
});
}
};
$scope.track = function(User) {
$scope.first(User);
};
function distance(User) {
var R = 6371; // km (change this constant to get miles)
var dLat = ($scope.lat2-$scope.lat1) * Math.PI / 180;
var dLon = ($scope.lon2-$scope.lon1) * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos($scope.lat1 * Math.PI / 180 ) * Math.cos($scope.lat2 * Math.PI / 180 ) * Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
$scope.User.d = R * c;
if ($scope.User.d>1) {
return Math.round($scope.d)+"km";
}
else {
if ($scope.User.d<=1) {
return Math.round($scope.d*1000)+"m";
}
}
return $scope.User.d;
};
$scope.starttrack = function(User) {
$scope.track(User);
$scope.addstring.push($scope.User.string1);
$scope.addstring1.push($scope.User.string1);
var values = $scope.User.string1.split(",");
$scope.lat1 = $scope.User.mysrclat;
$scope.lon1 = $scope.User.mysrclong;
$scope.lat2 = values[0];
$scope.lon2 = values[1];
distance();
$scope.User.timer = $interval(function() {
if($scope.addstring != "") {
$scope.track(User);
$scope.lat1 = $scope.lat2;
$scope.lon1 = $scope.lon2;
$scope.lat2 = $scope.User.mysrclat;
$scope.lon2 = $scope.User.mysrclong;
distance();
console.log($scope.User.d);
$scope.User.dis = $scope.User.dis + $scope.User.d;
$scope.addstring.push("|" + $scope.User.string1);
$scope.addstring1.push($scope.User.string1);
}
}, 10000);
};
$scope.getText = function(User){
return $scope.addstring.join("");
};
$scope.endtrack = function(User, d) {
if(angular.isDefined($scope.User.timer)) {
$interval.cancel($scope.User.timer);
$scope.User.timer = undefined;
$scope.User.string2 = $scope.addstring[0];
for(var i=1; i<($scope.addstring).length; i++) {
$scope.User.string2 = $scope.User.string2 + $scope.addstring[i];
}
$scope.User.coordinates = $scope.User.string2;
$scope.User.dis = $scope.User.dis + " KM";
console.log($scope.User.dis);
AllServices.drivertrackFunction(User)
.then(function(response) {
})
.catch(function(error) {
console.log(error);
});
}
};
$scope.dist = function() {
distance();
console.log($scope.User.d, "Km");
};
})
and this is my php code
<?php
include("connection.php");
$data = json_decode(file_get_contents("php://input"));
$coordinates = $data->coordinates;
$dis = $data->dis;
$q = "INSERT INTO track (Coordinates, Distance) VALUES (:coordinates, :dis)";
$query = $db->prepare($q);
$execute = $query->execute(array(
":coordinates" => $coordinates,
":dis" => $dis
));
echo json_encode($data);
?>

Incrementally add date with ng-repeat

I have a variable $scope.date in my controller. In the view, I do ng-repeat over a couple of items. Each item has a duration in minutes. How would I go about to incrementally add time for every repeat and display this?
Add a function on the controller that calculates the date including the duration. Working code snippet:
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
$scope.someDate = new Date();
$scope.durations = [1, 2, 5, 6, 8];
$scope.calculateIncrementalDuration = function(index) {
var sum = 0;
for (var i = 0; i <= index; i++) {
sum += $scope.durations[i];
}
return sum;
}
$scope.calculateEndDate = function(startDate, index) {
return new Date(startDate.getTime() + $scope.calculateIncrementalDuration(index) * 60000);
}
});
.delay {
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
Start time: {{someDate.toUTCString()}}
<div class="delay" ng-repeat="duration in durations">Duration in minutes: {{calculateIncrementalDuration($index)}}
<div>End time: {{calculateEndDate(someDate, $index).toUTCString()}}</div>
</div>
</div>
I don't have the reputation for a comment, so please don't be angry at me, those who get angry at non-answers as answers, but I would highly recommend looking into moment.js for things like this.

Calculate age from given year in AngularJS

I'm new for AngularJs. I have to calculate age from give year. How I can in PHP?
My script and view files are following,
My .Js:
function mycontroller($scope){
$scope.sales = [
{
name: 'steptoinstall',
year: 1986,
}
]; }
My view.php:
<li ng-repeat="sale in sales" >
{{sale.name}} {{ **AGE** }}
</li>
And,
If I have full date like '10-01-1989', then how can I?
If only year means,
view.PHP
<li ng-repeat="sale in sales" >
{{sale.name}} {{ yearToAge(sale.year) }}
</li>
.Js File:
$scope.yearToAge= function(y) {
return new Date().getFullYear() - y;
}
If Date format given,
view.PHP
<li ng-repeat="sale in sales" >
{{sale.name}} {{ dateToAge(sale.dob) }} // dob should be in dd/mm/yyyy format
</li>
.Js File:
$scope.dateToAge = function(date1){
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var today = curr_date + "-" + curr_month + "-" + curr_year;
var x = date1.split("-");
var y = today.split("-");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
var fdays = sdays - bdays;
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
return fyear;
}
Add this to your JS
$scope.ageFromYear = function(year) {
return new Date().getFullYear() - year;
}
Then, you can do this in your HTML:
<li ng-repeat="sale in sales" >
{{sale.name}} {{ ageFromYear(sale.year) }}
</li>
In PHP, the idea is built on converting the date into UNIX timestamp, then converting the current date too. then subtracting them, and finally dividing that number on the number of seconds in the year and get its floor to get the numbers of years.
This is a handled as following:
$d = '10-01-1989';
$dT = strtotime($d);
$cur = strtotime(date("m-d-Y"));
$diff = $cur - $dT;
$years = floor($diff/(60*60*24*365));
echo $years;
Checkout this DEMO: http://codepad.org/ErV8RauU

ngRepeat dont refresh when I change the values - AngularJS

I'm doing a application to a calendar and I create a function that everytime change the values of my variable called "$scope.days", when I was using the version 1.0 didnt give error, but now the ngRepeat doesnt refresh, the new values go to the variable, but the ngRepeat dont show the new result...
$scope.loadMonth = function()
{
$scope.titleCalendar = $scope.months[$scope.month-1].name + ' ' + $scope.year;
getTotalFebruary($scope.year);
var dtString = $scope.year + '/' + $scope.month + '/' + 1,
date = new Date(dtString),
day = 1,
weekday = date.getDay(),
totalDays = $scope.months[date.getMonth()].qty + date.getDay();
$scope.days = [];
for(var i = 0; i < totalDays; i++)
{
if(i < weekday)
$scope.days.push('');
else
$scope.days.push(day++);
}
};
my html:
<div class="day" ng-repeat="day in days"><p>{{ day }}</p></div>
If I put an alert after push new values, I can see the new values, but my ngRepeat doesnt refresh the results, I already try many things but didnt work. Somebody know the solution?
Not sure I understand what you are trying to achieve given the small sample of code you provided but if you look at this sample you'll see that it should update the display every time you click the click me text, just enter either 1,2, or 3 in the input area. you might want to check that looping logic of yours.
<html lang="en-US" ng-app="mainModule">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
</head>
<body>
<div ng-controller="mainController">
<input type="text" ng-model="monthModel" placeholder="enter 1 2 or 3"/>
<h1 ng-click="loadMonth(monthModel)">Click Me to Repeat</h1>
<span class="day" ng-repeat="day in days">{{ day }} , </span>
</div>
<script type="text/javascript">
var app = angular.module("mainModule", []);
app.controller("mainController", function ($scope) {
//$scope.monthModel = 1; // default some date
$scope.year = "2014";
$scope.months = [
{"name":"January", "qty":10},
{"name":"February", "qty":5},
{"name":"March", "qty":10},
];
$scope.loadMonth = function(monthModel)
{
$scope.month = monthModel;
$scope.titleCalendar = $scope.months[$scope.month-1].name + ' ' + $scope.year;
//getTotalFebruary($scope.year);
var dtString = $scope.year + '/' + $scope.month + '/' + 1,
date = new Date(dtString),
day = 1,
weekday = date.getDay(),
totalDays = $scope.months[date.getMonth()].qty + date.getDay();
$scope.days = [];
for(var i = 0; i < totalDays; i++)
{
//if(i < weekday)
// $scope.days.push('');
//else
$scope.days.push(day++);
console.log($scope.days) ;
}
};
});
</script>
</body>
</html>

Resources