Angular - Get days Of Week for weather info - angularjs

I want to get days of the week from data weather Json , I am using this code
'
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var date = new Date();
$scope.wDay = dayNames[date.getDay()];
html
{{wDay}}
get result only one day 'sun' not all days of week
full json data
{
"daily": {
"summary": "لا أمطار خلال الأسبوع مع درجات حرارة ترتفع حتى 50°C يوم الأربعاء",
"icon": "clear-day",
"data": [
{
"time": 1469912400,
"summary": "اجواء جافة خلال اليوم",
"icon": "clear-day",
"sunriseTime": 1469931375,
"sunsetTime": 1469981058,
"moonPhase": 0.91,
"precipIntensity": 0,
"precipIntensityMax": 0,
"precipProbability": 0,
"temperatureMin": 30.7,
"temperatureMinTime": 1469930400,
},

This program is time dependent.
new Date().getDay()
wil always retuen you 0 today

You will only see Sunday - as it's what you specifically test for it with:
dayNames[date.getDay()]; - number corresponding to the day of the week for the given date.
If you want them all, simply ng-repeat dayNames:
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var date = new Date();
function MyCtrl($scope) {
$scope.today = dayNames[date.getDay()];
$scope.all = dayNames;
}
Today is {{today}}!
<div ng-repeat="day in all">
{{day}}
</div>
http://jsfiddle.net/Lvc0u55v/7751/
Edit:
change in the scope of the question, so here's an addition to the answer. It can of course be written in a more condensed manner, but expanded for brevity:
http://jsfiddle.net/Lvc0u55v/7896/
I added MomentJS (http://momentjs.com) - great for working with dates.
//Added a filter to grab today's data from JSON
myApp.filter('GetToday',function(){
return function(epoch) {
//Get today
var today = moment();
//Loop through all the daily nodes from the JSON
for (var i = 0; i < epoch.length; i++) {
//convert UNIX timestamp to date
var json = moment.unix(epoch[i].time);
//determine difference between dates
var duration = moment.duration(json.diff(today));
//convert the difference into hours
var hours = duration.asHours();
//if it's more than 0 and less than 24 (today) return this node
if(hours > 0 && hours < 24) {
return epoch[i];
}
}
}
});
myApp.controller('MyCtrl', ['$scope', '$filter', function($scope, $filter){
$scope.daily = $filter('GetToday')(data[0].daily.data);
}]);

Related

Show Color on Specific dates in datetime-picker AngularJs

I'm using bootstrap datetime-picker in angularjs
I need to show color on some specific dates i.e. on weekend and holiday dates
Here is my date picker option :-
$scope.dateOptions = {
dateFormat: 'yyyy-MM-dd',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1,
onChangeDate: countDays
};
I'm getting list of holidays from database and weekends I'm able to identify.
How to show color to specific date?
I tried using some custom css but its applying on all the dates not to specific.
Thanks!
Answering your question
How to show color to specific date?
Bootstrap datetime-picker for Angularjs Do provide an option to apply custom class.
Try this
$scope.dateOptions = {
dateFormat: 'yyyy-MM-dd',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1,
onChangeDate: countDays,
customClass: getDayClass // fucntion having logic to select particular dates
};
The function getDayClass can be implement like this
function getDayClass(data) {
var date = data.date,
mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i = 0; i < $scope.events.length; i++) {
var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
// check for weekend 0 for sun and 6 for sat
if(date.getDay() == 0 || date.getDay() == 6)
{
return 'full'; //return class to be applied
}
}
return '';
}
Set the class for dates
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date(tomorrow);
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
The date picker calls date picker options for every date at the time of initialization.
you can check the Plunker example.

Google charts vAxis timespans

Hi Guys according to the documentation of google charts a row type can either be :
The type can be one of the following: 'string', 'number', 'boolean',
'date', 'datetime', and 'timeofday'.
https://developers.google.com/chart/interactive/docs/datesandtimes
I need to have timespan type, so I can have vAxis with values 0 hour, 1 hour, 2 hours, ....up to any number. Which will mean between each two is 60 degrees like a timespan, but not 100 degree like numbers.
Is there a way to acheive this? timeofday will not work also when reaching 24 hours it turns it into 00:00
using the option --> hAxis.ticks
combined with object notation for values --> {v: value, f: formattedValue}
you could probably use just about any type (other than 'string')
see the following working snippet for a basic example...
a custom set of hAxis.ticks is built, one tick for each hour, in a 48 hour timespan
google.charts.load('current', {
callback: function () {
drawChart();
window.addEventListener('resize', drawChart, false);
},
packages:['corechart']
});
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('date', 'Timespan');
dataTable.addColumn('number', 'Y');
var oneHour = (1000 * 60 * 60);
var startDate = new Date();
var endDate = new Date(startDate.getTime() + (oneHour * 24 * 2));
var ticksAxisH = [];
for (var i = startDate.getTime(); i < endDate.getTime(); i = i + oneHour) {
var tickValue = new Date(i);
var tickFormat = (tickValue.getTime() - startDate.getTime()) / oneHour;
var tick = {
v: tickValue,
f: tickFormat + 'h'
};
ticksAxisH.push(tick);
dataTable.addRow([tick, (2 * tickFormat) - 8]);
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(dataTable, {
hAxis: {
ticks: ticksAxisH
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to get the Days b/w current week in moment.js

I'm new to angular js and moment.js i have the following code which gives the start day and end day of a week like January 17th-January 23rd. but i want all the 7 days in this format january 17, monday.
My code
var currentDate,
weekStart,
weekEnd,
shortWeekFormat = 'MMMM Do';
function setCurrentDate(aMoment){
currentDate = aMoment,
weekStart = currentDate.clone().startOf('week'),
weekEnd = currentDate.clone().endOf('week')
}
setCurrentDate(moment());
$scope.currentWeek = function(){ return currentDate.format(shortWeekFormat); };
$scope.currentWeekStart = function(){ return weekStart.format(shortWeekFormat); };
$scope.currentWeekEnd = function(){ return weekEnd.format(shortWeekFormat); };
HTML
<h2><i class="fa fa-arrow-left"></i>Week Of {{currentWeek()}}{{currentWeekStart()}}-{{currentWeekEnd()}}<i class="fa fa-arrow-right"></i></h2>
<button ng-click="prevWeek()">previous week</button>
<button ng-click="nextWeek()">next week</button>
The format you want can be achieved with below moment code.
moment('01/19/2016').format("MMMM Do,dddd");
Now, to get all dates between a week you need to use array which holds all the seven dates for you. With simple for loop adding days to start date you can achieve what you want. Take a look at below sample code.
var currentDate = moment();
var weekStart = currentDate.clone().startOf('week');
var weekEnd = currentDate.clone().endOf('week');
var days = [];
for (i = 0; i <= 6; i++) {
days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
};
console.log(days);
console.log(moment('01/19/2016').format("MMMM Do,dddd"));
Now to use it with angular you can assign days array to some scope variable and use ng-repeat to display dates.
JSFiddle
Improving J-D's answer. This will return an array of moment objects:
const getCurrentWeekDays = () => {
const weekStart = moment().startOf('week');
const days = [];
for (let i = 0; i <= 6; i++) {
days.push(moment(weekStart).add(i, 'days'));
}
return days;
}

Display data in bar chart using angular-chart

I am trying to display data on a bar chart using angular-chart. I am trying retrieving the data from a database. I want to display all data on the chart for the last five (5) years including this year and also get the data to correspond with the years. So far I am only using 2 yrs, as shown below.
Json Array
Angularjs
app.controller('ChartCtrl', ['$scope', '$http', function ($scope, $http) {
var currentYear = new Date().getFullYear();
var allYrs = [];
// get data from database
$http.get('/dashboard/incident').success(function(incidents) {
$scope.incidentCnt = incidents;
console.log($scope.incidentCnt);
for (var i = 0; $scope.incidentCnt.length; i++) {
// Gets the current year and last 4 years (5 yrs total)
for(var year = currentYear; year >= currentYear-4; year--) {
allYrs.push(year);
$scope.labels = allYrs; // display years
$scope.series = [
'Aggravated Assault',
'Arson',
'Burglary',
'Forcible Sex Offense',
'Hate Crime',
'Motor Vehicle Theft',
'Murder or Non-Negligent Manslaughter',
'Negligent Manslaughter',
'Non-Forcible Sex Offense',
'Relationship/Dating Violence',
'Robbery',
'Stalking'
];
$scope.data = [
[
$scope.incidentCnt[i].assault,
$scope.incidentCnt[i].arson,
$scope.incidentCnt[i].burglary,
$scope.incidentCnt[i].fSexOffense,
$scope.incidentCnt[i].hateCrime,
$scope.incidentCnt[i].vehicleTheft,
$scope.incidentCnt[i].nonNegligentMaslaughter,
$scope.incidentCnt[i].negligentMaslaughter,
$scope.incidentCnt[i].nonForcibleSexOffense,
$scope.incidentCnt[i].rshipDatingViolence,
$scope.incidentCnt[i].robbery,
$scope.incidentCnt[i].stalking
]
];
}
};
});
}]);
Chart's current look
Any help would be much appreciated. Thank you...
I would simply create a custom filter to show last 5 years data
Filter
app.filter('for5Years', function(){
return function(values){
var returnValues = [],
date = new Date(),
currentYear = date.getFullYear(),
limitYear = currentYear - 4;
angular.forEach(values, function(value, index){
if(value.incidentyear <= currentYear && value.incidentyear >= limitYear){
returnValues.push(value);
}
});
return returnValues;
}
});
Controller
app.controller('ChartCtrl', ['$scope', '$http', '$filter', function($scope, $http, $filter) {
var currentYear = new Date().getFullYear();
var allYrs = [];
// get data from database
$http.get('/dashboard/incident').success(function(incidents) {
$scope.incidentCnt = $filter('for5Years')(incidents); //this line will do filtering for you.
console.log($scope.incidentCnt);
//$scope.labels = allYrs; // display years logic to do
for (var i = 0; $scope.incidentCnt.length; i++) {
$scope.series = [
'Aggravated Assault',
'Arson',
'Burglary',
'Forcible Sex Offense',
'Hate Crime',
'Motor Vehicle Theft',
'Murder or Non-Negligent Manslaughter',
'Negligent Manslaughter',
'Non-Forcible Sex Offense',
'Relationship/Dating Violence',
'Robbery',
'Stalking'
];
$scope.data = [
[
$scope.incidentCnt[i].assault,
$scope.incidentCnt[i].arson,
$scope.incidentCnt[i].burglary,
$scope.incidentCnt[i].fSexOffense,
$scope.incidentCnt[i].hateCrime,
$scope.incidentCnt[i].vehicleTheft,
$scope.incidentCnt[i].nonNegligentMaslaughter,
$scope.incidentCnt[i].negligentMaslaughter,
$scope.incidentCnt[i].nonForcibleSexOffense,
$scope.incidentCnt[i].rshipDatingViolence,
$scope.incidentCnt[i].robbery,
$scope.incidentCnt[i].stalking
]
];
}
});
}]);

Convert birthday to age in angularjs

I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.
i am displaying date like :
{{ friend.birthday }}
How can i display age instead of displaying birthday.
if it is possible to create filters than how to create filter and how to apply it.
You can implement a function:
Controller:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
HTML
{{ calculateAge(friend.birthday) }}
Or a filter:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
HTML
{{ friend.birthday | ageFilter }}
Age algorithm taken from this SO answer.
[EDIT] If the age is less than 1 year, and you want to show months, you can modify the ageFilter to calculate the month difference:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function monthDiff(d1, d2) {
if (d1 < d2){
var months = d2.getMonth() - d1.getMonth();
return months <= 0 ? 0 : months;
}
return 0;
}
return function(birthdate) {
var age = calculateAge(birthdate);
if (age == 0)
return monthDiff(birthdate, new Date()) + ' months';
return age;
};
});
Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year
If you're value is just for example "05/01/2016". This will be a useful code to convert the date to birthday.
AngularJS
app.filter('ageFilter', function(){
return function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
});
HTML
{{ relationTypePreDefined.birthdate | ageFilter }}
By the way I used this solution to convert a date coming from a jquery datepicker input to age.
If you are using momentjs. Then you can create filter simply by using this snippet
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
Idk why I can never reply to people, says I need more rep but to rep I need to comment.. whatever.
In response to #Dean Christian Armada's, I kept getting an error regarding the filter. But changing to the following seems to work fine so I do appreciate it!
$scope.getAge = function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
And for the HMTL
{{ getAge(birthdate) }}

Resources