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

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;
}

Related

How to modify This angularjs function to retrieve range between two dates

How can I modify this angular function to retrieve range of dates. For now its looping 20 times. How can I only retrieve date from Date().getFullYear(); --> Which is current year till 2020. So in range it should display 2017, 2018, 2019, 2020.
$scope.myfunction = function () {
var year = new Date().getFullYear();
var range = [];
range.push(year);
for (var i = 1; i < 20; i++) {
range.push(year + i);
}
return range;
}
<select ng-options="year for year in myfunction()" name="year" ng-model="year" required>
<option value selected disabled>select year</option>
</select>
You can do something like this. You can set the end year or pass to the function as an argument.
$scope.myfunction = function (endYear) {
var range = [];
var startYear = new Date().getFullYear();
endYear = endYear || 2020;
while ( startYear <= endYear ) {
range.push(startYear++);
}
return range;
}

angular material date picker field value empty

I want to get date of birth of a user, with predefined min and max date which is working fine.
And the date format i want is DD-MM-YYYY, for this i have defined following in config;
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
and the controller has
$scope.user = {};
$scope.user.dob = new Date();
$scope.maxDate = new Date(
$scope.user.dob.getFullYear() - 10,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
$scope.minDate = new Date(
$scope.user.dob.getFullYear() - 120,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
and the HTML is;
<md-datepicker
ng-model="user.dob"
md-placeholder="Enter date of birth"
md-min-date="minDate"
md-max-date="maxDate">
</md-datepicker>
with this code the field shows current date by default, which i don't want,
i want the date field to be empty by default.
Also i want to get values in both ways as follows
1) date-month-year
And
2) date-month-year hour-minutes-seconds
When i tried to get the value it shows this "09-11-2016T18:30:00.000Z"
i want either "09-11-2016" or "09-11-2016 18:30:00"
Your mdDateLocaleProvider doesnt check for null values.
Your Problem is:
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
it needs to be something like:
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
return m.isValid()? m.format('DD-MM-YYYY') : '';
};
Then you can set
$scope.user.dob=null;
And get an empty Datepicker.
The problem is your ng-model. You're initializing it with the current date:
$scope.user.dob = new Date();
Simply empty this variable and you'll be good ;)

Angular - Get days Of Week for weather info

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);
}]);

AngularJS Filter Posts by Date not showing today's date

I've got a list of events on a site I'm building and I would like the past events to be removed automatically. I've written a filter that is doing this, except it is removing today's events as well. I'm trying to use Angular Moment. Here is my code:
angular.module('zenCityApp')
.filter('filterPastDates', function (moment) {
return function (events) {
var filterByDate = [];
for (var i = 0; i < events.length; i++) {
var currentDate = new Date();
if(moment(currentDate).isBefore(events[i].date, 'hour')) {
console.log("we're in!");
filterByDate.push(events[i]);
console.log(filterByDate);
}
}
return filterByDate;
};
});
And here is the markup:
div ng-repeat="event in events | limitTo:100 | filter:tfilter | orderBy: 'date' | filterPastDates">
<div class="row">
<div class="col-md-6">
<h4>{{event.date | amDateFormat:'MMMM Do'}}</h4>
</div>
<div class="col-md-6">
<h4>{{event.name}}</h4>
</div>
</div>
Any help would be greatly appreciated.
What would be better is to create a cut-off moment for which you want to test. Moments api gives you a pretty easy way to do it by using .startOf('day'). That will give you a moment that represents today at 12:00am (the first second in the day). But since you also want to include that value in your filter, you can then subtract 1 millisecond from the value.
var cutOffDate = moment().startOf('day').subtract(1,'millisecond');
And now you can easily use that in your filter. Notice that I created that object outside of the loop (since it's not supposed to change), and I created it as a moment directly instead of creating a new moment object each time in the loop.
app.filter('filterPastDates', function () {
return function (events) {
if (events && events.length) {
var filtered = [];
var cutOffDate = moment().startOf('day').subtract(1,'millisecond');
for (var i = 0; i < events.length; i++) {
var evt = events[i];
if (cutOffDate.isBefore(evt.date)) {
filtered.push(evt);
}
}
return filtered;
} else {
return events;
}
};
});
Here's a sample plunker: http://plnkr.co/edit/kSXu0Z3J7zoyBMBjoE84?p=preview

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