Angular to display last 12 months dates - angularjs

I am trying to write simple ng-repeat that displays a list of the last 12 months, from today.
So for example, if i load my application today (May 2014), i will have a list of:
May 2014
Apr 2014
Mar 2014
Feb 2014
Jan 2014
Dec 2013
Nov 2013
Oct 2013
Sep 2013
Aug 2013
Jul 2013
Jun 2013
If i was to view on say, September 2014, then the list would display as:
Sep 2014
Aug 2014
Jul 2014
Jun 2014
May 2014
Apr 2014
Mar 2014
Feb 2014
Jan 2014
Dec 2013
Nov 2013
Oct 2013
HTML:
<div ng-app="">
<div ng-controller="Ctrl">
<li ng-repeat="currMonth in months">{{currMonth}}</li>
</div>
</div>
JS:
function Ctrl($scope) {
$scope.months = [
"01 - Jan",
"02 - Feb",
"03 - Mar",
"04 - Apr",
"05 - May",
"06 - Jun",
"07 - Jul",
"08 - Aug",
"09 - Sep",
"10 - Oct",
"11 - Nov",
"12 - Dec"
];
$scope.month = 'null';
}

The logic is fairly simple and really not anything angularjs related. That being said, I wanted to try it out for myself and this is what I came up with.
angular.module('test', []).controller('Ctrl', function($scope) {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
for(var i = 0; i < 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
// Subtract a month each time
date.setMonth(date.getMonth() - 1);
}
$scope.months = months;
});
Here's the jsfiddle I used to create it.

Since we are using angular, take advantage on $filter directives
angular.module('test', []).controller('Ctrl', function($scope, $filter) {
$scope.premonths = 12;
$scope.getMonths = function(){
$scope.months = [];
var today = new Date();
var endDate = new Date()
endDate.setMonth(endDate.getMonth() - $scope.premonths)
for(var d=today;d > endDate;d.setMonth(d.getMonth() - 1)) {
$scope.months.push({month:($filter('date')(d, 'MMMM')),year:$filter('date')(d, 'yyyy')})
}
}
$scope.getMonths();
});
input {
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app='test'>
<body ng-controller='Ctrl'>
Get last <input ng-model='premonths' ng-change='getMonths()'> months
<ul>
<li ng-repeat='month in months'>
{{month.month}} - {{ month.year}}
</li>
</ul>
</body>
</html>

Related

How to display Firestore datetime [duplicate]

I'm pulling a timestamp from a Firestore database, and I only want to display the date to the user. The original timestamp is
Timestamp(seconds=1555477200, nanoseconds=0)
I've tried a few variations to get the Date, but they all have the same output-
Due: Wed Apr 17 2019 06:10:21 GMT-0500 (Central Daylight Time)
<p>Due: ${Date(dueDate)}<br>
<p>Due: <time>${Date(dueDate)}</time><br>
<p>Due: <time type="date">${Date(dueDate)}</time><br>
How do I cut off the time part of the timestamp?
(Ideally, I'd want "April 17, 2019", but if the day is in there that's fine too)
If you have a particular format for date, you can do
function getDate (timestamp=Date.now()) {
const date = new Date(timestamp);
let dd = date.getDate();
let mm = date.getMonth()+1; //January is 0!
const yyyy = date.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
// Use any date format you like, I have used YYYY-MM-DD
return `${yyyy}-${mm}-${dd}`;
}
getDate(1555477200000);
// -> 2019-04-17
Alternatively, you can also do:
const time = new Date(1555477200000);
// -> Wed Apr 17 2019 10:30:00 GMT+0530 (India Standard Time)
const date = time.toDateString();
// -> Wed Apr 17 2019
P.S: I have used ES6 here. If you are working on ES5, use babel's online transpiler to convert.
Link: https://babeljs.io/repl
You can do
var time= timeStampFromFirestore.toDate();
console.log(time);
console.log(time.toDateString());
See the full documentation :
toDateString()
toDate()
You can use Date.toLocaleString() like this:
new Date(date).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' });
const timestamp = 1555477200000;
console.log(
new Date(timestamp).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' })
);
Simply use moment.js and use your required format
date = moment();
console.log(date.format("MMMM D, YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

React Native Create Components with multiple condition

I have a data structure like this:
const _ = require('lodash');
const bills = [
{year:2021, month:5, bill:'bill in 2021 may'},
{year:2018, month:1, bill:'bill in 2018 jan'},
{year:2019, month:1, bill:'bill in 2019 jan'},
{year:2018, month:2, bill:'bill in 2018 feb'},
{year:2019, month:10,bill:'bill in 2019 oct'},
{year:2019, month:2, bill:'bill in 2019 feb'},
{year:2019, month:6, bill:'bill in 2019 jun'},
{year:2020, month:11,bill:'bill in 2020 nov'}
];
and I want to display like below using Text or Card component of native-base
2018
1
bill in 2018 jan
2
bill in 2018 feb
2019
1
bill in 2019 jan
2
bill in 2019 feb
6
bill in 2019 jun
10
bill in 2019 oct
2020
11
bill in 2020 nov
2021
5
bill in 2021 may
My codes are below using lodash library to generate above and display in the terminal
// sort the data first
let arrSortedTasks = _.orderBy(tasks, ['year', 'month'],['asc']);
// get all the different year from the data
let arrUniqYear = _.uniqBy(arrSortedTasks, 'year');
// get all the different month from the data
let arrUniqMonth = _.uniqBy(arrSortedTasks, 'month');
// take out only the value of the year
arrUniqYear =_.map(arrUniqYear, 'year');
// take out only the value of the month
arrUniqMonth =_.map(arrUniqMonth, 'month');
let taskList = '';
for (let year of arrUniqYear) {
console.log(year);
for (let month of arrUniqMonth) {
let displayMonth = false;
for (let obj of arrSortedTasks) {
if (obj.year === year && obj.month === month) {
taskList = taskList + obj.task;
displayMonth = true;
}
}
if (displayMonth) {
console.log(" " + month);
}
if (taskList.length > 0) {
console.log(" " + taskList);
}
taskList = '';
}
}
How can we display the components in react-native with native-base? SO here don't let me post if too many code sigh. I tried a few ways buy got errors and can't figure out.
I end up using array as a return object in rendering
renderBillsSection() {
const { bills } = this.props;
if(bills || bills.length > 0 ) {
let arrSortedTasks = _.orderBy(tasks, ['year', 'month'],['asc']);
let arrUniqYear = _.uniqBy(arrSortedTasks, 'year');
let arrUniqMonth = _.uniqBy(arrSortedTasks, 'month');
let billList = '', arr = [], yearIndex = 0, monthIndex = 0, billIndex = 0;
arrUniqYear = _.map(arrUniqYear, 'year');
arrUniqMonth = _.map(arrUniqMonth, 'month');
for (let year of arrUniqYear) {
arr.push(<Text key="{yearIndex}">{year}</Text>)
yearIndex++
for (let month of arrUniqMonth) {
let displayMonth = false;
for (let obj of arrSortedTasks) {
if (obj.year === year && obj.month === month) {
billList = billList + obj.task
displayMonth = true
}
}
if (displayMonth) {
arr.push(<Text key="{monthIndex}" style={{marginLeft:10}}>{month}</Text>)
monthIndex++
}
if (billList.length > 0) {
arr.push(<Text key="{taskIndex}" style={{marginLeft:20}}>{billList}</Text>)
billIndex++
}
billList = '';
}
}
return arr;
}
}
not sure about how you are planning to render it in UI, but if you want to have the data structure like this, you need to group it (and sort by monhts if its not already sorted)
_(bills).groupBy('year').map((v,k)=> ({year: k, docs: _.sortBy(v,'month')})).value()
it will give you another array where you have year, abd docs as nested array holding all the documents of that year, so that you can agaib have another repeat on that.
const bills = [
{year:2021, month:5, bill:'bill in 2021 may'},
{year:2018, month:1, bill:'bill in 2018 jan'},
{year:2019, month:1, bill:'bill in 2019 jan'},
{year:2018, month:2, bill:'bill in 2018 feb'},
{year:2019, month:10,bill:'bill in 2019 oct'},
{year:2019, month:2, bill:'bill in 2019 feb'},
{year:2019, month:6, bill:'bill in 2019 jun'},
{year:2020, month:11,bill:'bill in 2020 nov'}
]
let groupedDoc = _(bills).groupBy('year').map((v,year)=> ({year, docs: _.sortBy(v,'month')})).value();
console.log(groupedDoc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
Here is a working snippet:
I think you should do :
const gropuByYear = _.groupBy(bills,'year');
console.log(_.map(groupByYear, groups =>
groups.forEach(group=>(<View> {obj.bill}</View>)))
even you can orderBy year desc first then do the loop good luck
You need to take a look at SectionList of React Native.
Checkout this example and cuiyueshuai for more practical example.
SectionList Demo:
<SectionList
renderItem={({ item, index, section }) => <Text key={index}>{item}</Text>}
renderSectionHeader={({ section: { title } }) => <Text style={{ fontWeight: 'bold' }}>{title}</Text>}
sections={[
{ title: 'Title1', data: ['item1', 'item2'] },
{ title: 'Title2', data: ['item3', 'item4'] },
{ title: 'Title3', data: ['item5', 'item6'] },
]}
keyExtractor={(item, index) => item + index} />

Converting IST to local time in angular js

From server I am getting time in this format "21/11/2017 17:01:30", and this time is in IST. I want to convert this time to the users local time.
I am using below given code for that,
var startDateTimeArray = eachExeRun.startDate.split(" ");
var startDateArray = startDateTimeArray[0].split("/");
var startDate = new Date(startDateArray[2]+"-"+startDateArray[1]+"-"+startDateArray[0]+' '+startDateTimeArray[1]);
And now my startDate is "Tue Nov 21 2017 16:59:29 GMT+0530 (India Standard Time)"
In html I used like this
{{startDate | date:'yyyy-MM-dd HH:mm:ss'}}
After this to test my code I changed my system's timezone to pasific time zone, then my startTime changed to "Tue Nov 21 2017 16:59:29 GMT-0800 (Pacific Standard Time)", but in my view still its showing "2017-11-21 16:59:29".
How can I display updated time without using timezone in date filter(date:'yyyy-MM-dd HH:mm:ss Z').
Using moment.js is the beat way.
However, you could also write a custom filter for converting the dates.
Try this:
app.filter('myFormat', function() {
return function(x) {
var startDateTimeArray = x.split(" ");
var startDateArray = startDateTimeArray[0].split("/");
var startDate = new Date(startDateArray[2]+"-"+startDateArray[1]+"-"+startDateArray[0]+' '+startDateTimeArray[1]);
console.log(startDate);
//from timezone
var IST_timezone_offset = -330; // IST timezone offset -always known
var req_UTC_Milliseconds = (IST_timezone_offset * 60000) ;
//to timezone
var local_timezone_offset = startDate.getTimezoneOffset();
var local_UTC_Milliseconds = (local_timezone_offset * 60000);
var final_date = new Date( startDate.getTime() + (req_UTC_Milliseconds - local_UTC_Milliseconds ) );
return final_date;
};
});
Working Fiddle
Using momentJs it is quite simple:
Find the working code snippet below:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
<body>
<h2>My IST to Local System Date Convertor</h2>
<div ng-app="myApp" ng-controller="dateCtrl">
<p>{{convertIstToSystemLocalDateUsingTimeZone(IstStartDate)}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('dateCtrl', function ($scope) {
$scope.IstStartDate = '21/11/2017 17:01:30';
$scope.convertIstToSystemLocalDateUsingTimeZone = function (incomingISTString) {
return moment.tz(incomingISTString, 'DD-MM-YYYY HH:mm:ss', 'Asia/Kolkata')
.local().format('DD-MM-YYYY HH:mm:ss');
}
});
</script>
</body>
</html>

Get date to display just month and year AngularJS, Firebase

I'm confused about how to get a date to display just a month and year using angularJS and Firebase.
I have converted a date to a string to be saved in Firebase.
Let me clarify that the date that is saved is not the current date, and is not supposed to represent the creation date of the post. It is a date that is chosen with a date picker (It is supposed to represent a past completion date of a project).
This is how the date is saved in firebase:
It is a string saved as Mon Jan 25 2016 00:00:00 GMT-0500 (EST)
Here is how it is displayed in the browser. This is just one "article" of many:
I'm trying to get it to display as just "January 2016"
I'm not sure how to get it back to a date instead of a string, and then filter it so it is just the month and the year.
Here is the relevant HTML:
<body ng-controller="WelcomeCtrl">
<div class="list-group" ng-repeat="article in articles">
<a href="#" onclick="return false;" class="list-group-item active">
<h4 class="list-group-item-heading">{{article.title}}</h4>
<p class="list-group-item-text">Completed: {{article.date}}</p>
<p class="list-group-item-text"><em>{{article.tech}}</em></p>
<p class="list-group-item-text">{{article.post}}</p>
<span class="pull-right">
<button class="btn btn-xs btn-info" ng-click="editPost(article.$id, article.date)" data-target="#editModal">EDIT</button>
<button class="btn btn-xs btn-warning" ng-click="confirmDelete(article.$id)" data-target="#deleteModal" >DELETE</button>
</span>
</a>
</div>
</body>
Here is my WelcomeCtrl controller:
.controller('WelcomeCtrl', ['$scope', '$firebase', 'CommonProp', function ($scope, $firebase, CommonProp) {
$scope.username = CommonProp.getUser();
var firebaseObj = new Firebase("https://xxxxxxxx.firebaseio.com/articles");
var sync = $firebase(firebaseObj);
$scope.articles = sync.$asArray();
//I AM ASSUMING SOMETHING HAS TO GO RIGHT HERE TO CONVERT THE DATE TO A DATE OBJECT, BUT I AM NOT SURE WHAT.
//article.date = new Date(article.date); does not work.
//articles.date = new Date(articles.date); does not work.
$scope.editPost = function (id, date) {
console.log(id);
console.log(date);
var firebaseObj = new Firebase("https://xxxxxxx.firebaseio.com/articles/" + id);
var syn = $firebase(firebaseObj);
$scope.postToUpdate = syn.$asObject();
$scope.postToUpdate.date = new Date(date);
$('#editModal').modal();
};
$scope.update = function () {
console.log($scope.postToUpdate.$id);
var fb = new Firebase("https://xxxxxxxx.firebaseio.com/articles/" + $scope.postToUpdate.$id);
var article = $firebase(fb);
article.$update({
title: $scope.postToUpdate.title,
tech: $scope.postToUpdate.tech,
date: $scope.postToUpdate.date.toString(),
post: $scope.postToUpdate.post,
emailId: $scope.postToUpdate.emailId
}).then(function (ref) {
console.log(ref.key()); // bar
$('#editModal').modal('hide');
}, function (error) {
console.log("Error:", error);
});
};
$scope.confirmDelete = function (id) {
var fb = new Firebase("https://xxxxxxxx.firebaseio.com/articles/" + id);
var article = $firebase(fb);
$scope.postToDelete = article.$asObject();
$('#deleteModal').modal();
};
$scope.deletePost = function () {
var fb = new Firebase("https://xxxxxxxx.firebaseio.com/articles/" + $scope.postToDelete.$id);
var article = $firebase(fb);
article.$remove().then(function (ref) {
$('#deleteModal').modal('hide');
}, function (error) {
console.log("Error:", error);
});
};
}]);
You can parse the string representing the date to get the number of milisconds from Jan the 1st, 1970. Then use it to create a date object, from which you can extract the number of the month (from 0 to 11) and the year.
var months= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var milis = Date.parse("Mon Jan 25 2016 00:00:00 GMT-0500 (EST)");
var d = new Date(milis)
console.log(months[d.getMonth()] + " " + d.getFullYear());
will display "January 2016"
So in your code it should look like this if I'm correct:
var months= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
for(var i=0; i<$scope.articles.length;i++) {
var milis = Date.parse($scope.articles[i].date);
var d = new Date(milis)
$scope.articles[i].date = months[d.getMonth()] + " " + d.getFullYear();
}

AngularJS - Displaying Date Data For Items Only In The Last Five Years

I have a $scope.myData object that contains a list of addresses and dates that i've own/rented, eg:
Example of my data
From Date 2011 To Date current
From Date 2010 To Date 2011
From Date 2009 To Date 2010
From Date 2003 To Date 2004
What i am trying to do is output a statement that displays the years that i have owned/rented in the last 5 years.
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.myData = {
"Entries": [{
"EntryNumber": "E1",
"FromDt": "/Date(1320912000000)/",
"ToDt": null,
"RegisteredWith": "test"
}, {
"EntryNumber": "A1",
"FromDt": "/Date(1276153200000)/",
"ToDt": "/Date(1320912000000)/",
"RegisteredWith": "test"
}, {
"EntryNumber": "X1",
"FromDt": "/Date(1239346800000)/",
"ToDt": "/Date(1276153200000)/",
"RegisteredWith": "test"
}, {
"EntryNumber": "Z1",
"FromDt": "/Date(1063177200000)/",
"ToDt": "/Date(1086850800000)/",
"RegisteredWith": "test"
}
]
}
});
HTML:
<p>
In the last 5 years i have had addresses during (from {{ myData.Entries.FromDt.substring(6, myData.Entries.FromDt.length - 2) | date:'yyyy' }} to {{ }}, {{ }} to {{ }}, {{ }} to {{ }} and {{ }} to {{ }}).
</p>
Example of expected output:
<p>
In the last 5 years i have had addresses during (from 2011 to current, 2010 to 2011 and 2009 to 2010)
</p>
Here's a plunker: http://plnkr.co/edit/N55Zlb2ahjgovoVwTV63?p=preview
It looks like you need to use a filter and ng-repeat on a <span>. Your logic is largely correct in your ng-repeat of <li>s. You can just move that into a <span> to keep everything between your parentheses.
index.html:
<p>
In the last 5 years i have had addresses during (<span ng-repeat="data in myData.Entries | filter:onlyLastFiveYears"> -from {{ parseDate(data.FromDt) }} to {{ parseDate(data.ToDt) }}</span>)
</p>
app.js:
app.controller('MainCtrl', function($scope) {
// ...
$scope.parseDate = function(date) {
return ((date === null && 'current') || new Date(parseInt(date.substring(6, date.length - 2))).getFullYear())
}
$scope.onlyLastFiveYears = function(data) {
var currentYear = new Date().getFullYear();
var houseYear = $scope.parseDate(data.FromDt);
return (currentYear - houseYear <= 5);
}
});
I've edited your plunkr here. Good luck!

Resources