How to get month name from month number - angularjs

month=[1,2,3,4,5,6,7,8,9]
This array I am getting from server. How to get Month Name?
Till now I tried this:
var populateChartData = function (data) {
var getMonth = [];
var getProfit = [];
$scope.chartTitle = 'Year :' + moment().year();
data.forEach(function (obj) {
console.log(obj.month);
getMonth.push(moment().month(obj.month).format('MMM'));
});
console.log(getMonth);
};
but in console I'm getting
["Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"]
I should get like this
["Jan","Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep"]

you could just create your own filter like this: otherwise, pass the index into one function and get Month Name
myApp.filter('monthName', [function() {
return function (monthNumber) { //1 = January
var monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December' ];
return monthNames[monthNumber - 1];
}
}]);

0 corresponds to January, 1 to February and so on (from 0 to 11). It is done in such way because indexing usually starts from 0. Hence from programming point of view 0 is a good choice for January

In momentjs month number starts from 0.
You can see this documentation from moment
momentjs month

I think you should try from 0 index in the month array.or while iterating that array put -1 for that value.

I did as below
var populateChartData = function (data) {
var getMonth = [];
var getProfit = [];
data.forEach(function (obj) {
getMonth.push(moment().month(obj.month-1).format('MMM'));
});
console.log(getMonth);
};

Related

I want to convert month number to month name in ReactJs

This is the data in json file. the _id i am passing is month number.
Const incomes = [
{
"_id": 6,
"total": 3000
},
{
"_id": 7,
"total": 3500
}
]
I am trying to convert the month number to month name by using this function. but its not working.
const monthNames = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
const data = useMemo(
() => incomes.map((income, monthNames) => ({ ...income, name: monthNames[income._id.getMonth()] }
)
), [incomes, monthNames]);
Try this!
I think when you passed the monthNames in the .map it declared it as a new variable and that's why the result was undefined.
P.S. Added -1 to income._id so the months would match
Hope it helps :)
const incomes = [
{
"_id": 6,
"total": 3000
},
{
"_id": 7,
"total": 3500
}
]
const monthNames = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
const data = useMemo(
() => incomes.map((income) => ({ ...income, name: monthNames[income._id -1]}
)
), [incomes, monthNames]);

How to properly initialize array of structures inside another structure and return it from function?

I have an array of such structures:
typedef struct month {
char cName[20];
char cAbbr[20];
int iDays;
int iNumber;
} MONTH;
which is nested in another structure:
typedef struct input{
MONTH * pMonths;
DATE sDate;
CALCS sCalcs;
} INPUT;
I initialize this array of structs in stack like that:
MONTH * init_months(bool bLeap) {
MONTH months[NUM_MONTHS] = {
{ .cName = "January", .cAbbr = "Jan", .iDays = 31, .iNumber = 1 },
{ "February", "Feb", 28, 2 },
{ "March", "Mar", 31, 3 },
{ "April", "Apr", 30, 4 },
{ "May", "May", 31, 5 },
{ "June", "Jun", 30, 6 },
{ "July", "Jul", 31, 7 },
{ "August", "Aug", 31, 8 },
{ "September", "Sep", 30, 9 },
{ "October", "Oct", 31, 10 },
{ "November", "Nov", 30, 11 },
{ "December", "Dec", 31, 12 }
};
if(bLeap){
months[1].iDays++;
}
return months;
}
The question is, if i form a INPUT structure inside some function:
INPUT GetUserInput(void){
// init months
MONTH * pMonths;
pMonths = init_months(isLeap(sDate.iYear));
// some code here
...
INPUT sInput = { pMonths, sDate, sCalcs };
// return
return sInput;
}
then how to properly initialize array of MONTH and/or how to properly initialize INPUT so it would contain valid data when returned from GetUserInput() ?
You have 3 options:
Make it static (but all returned references will reference the same array).
static MONTH months[NUM_MONTHS] = {
Use malloc and compound literal
MONTH *months = malloc(sizeof(*months) * NUM_MONTHS);
/* check if memory was allocated */
memcpy(months, (MONTH[]){
{ .cName = "January", .cAbbr = "Jan", .iDays = 31, .iNumber = 1 },
{ "February", "Feb", 28, 2 },
{ "March", "Mar", 31, 3 },
{ "April", "Apr", 30, 4 },
{ "May", "May", 31, 5 },
{ "June", "Jun", 30, 6 },
{ "July", "Jul", 31, 7 },
{ "August", "Aug", 31, 8 },
{ "September", "Sep", 30, 9 },
{ "October", "Oct", 31, 10 },
{ "November", "Nov", 30, 11 },
{ "December", "Dec", 31, 12 }}, sizeof(*months) * NUM_MONTHS);
Wrap the table into another structure and return by value
typedef struct
{
MONTH months[NUM_MONTHS];
}YEAR;
YEAR init_months(bool bLeap) {
YEAR year = {{
{ .cName = "January", .cAbbr = "Jan", .iDays = 31, .iNumber = 1 },
{ "February", "Feb", 28, 2 },
{ "March", "Mar", 31, 3 },
{ "April", "Apr", 30, 4 },
{ "May", "May", 31, 5 },
{ "June", "Jun", 30, 6 },
{ "July", "Jul", 31, 7 },
{ "August", "Aug", 31, 8 },
{ "September", "Sep", 30, 9 },
{ "October", "Oct", 31, 10 },
{ "November", "Nov", 30, 11 },
{ "December", "Dec", 31, 12 }}};
if(bLeap){
year.months[1].iDays++;
}
return year;
}

How to sort an array of strings representing month and year?

I have an array of strings in my code which represents a series of months in years. Something like this:
let arrayOfMonths = ["May 2017", "January 2018", "August 2016", "January 2015", "June 2017"]
I'd like to sort it, by following the classic succession of months and years, so I'd like an output like this:
let sortedArrayOfMonths = ["January 2015", "August 2016", "May 2017", "June 2017", "January 2018"]
How can I do it in Swift 3? Thanks.
Why not simply
let formatter : DateFormatter = {
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "MMMM yyyy"
return df
}()
let arrayOfMonths = ["May 2017", "January 2018", "August 2016", "January 2015", "June 2017"]
let sortedArrayOfMonths = arrayOfMonths.sorted( by: { formatter.date(from: $0)! < formatter.date(from: $1)! })
I searched a bit more and I found the method ".sorted()" in Swift 3, so I built my working solution. I post in case someone needs:
let monthForNumber = ["January":1, "February":2, "March":3, "April":4, "May":5, "June":6, "July":7, "August":8, "September":9, "October":10, "November":11, "December":12]
For semplicity, I created the struct "Month", with "name" property and "year" property, I'll use the object month:
let month_1 = Month.init(name: "May", year: 2016)
let month_2 = Month.init(name: "April", year: 2010)
let month_3 = Month.init(name: "April", year: 2009)
let month_4 = Month.init(name: "January", year: 2026)
let month_5 = Month.init(name: "June", year: 2016)
let unsortedMonthsArray = [Month]()
unsortedMonthsArray.append(month_1)
unsortedMonthsArray.append(month_2)
unsortedMonthsArray.append(month_3)
unsortedMonthsArray.append(month_4)
unsortedMonthsArray.append(month_5)
let sortedArrayOfMonths = self.unsortedMonthsArray?.sorted(by: { (month1, month2) -> Bool in
if self.monthForNumber[month1.name!] != self.monthForNumber[month2.name!] {
if month1.year != month2.year {
return month1.year < month2.year
} else {
return self.monthForNumber[month1.name!]! < self.monthForNumber[month2.name!]!
}
} else {
if month1.year != month2.year {
return month1.year < month2.year
} else {
return self.monthForNumber[month1.name!]! < self.monthForNumber[month2.name!]!
}
}
})
This solution will give a sorted array of Months, that can be easily transformed into an array of strings ("monthName_monthYear").
You could also have done this:
let sortedMonths = arrayOfMonths.map{($0,$0.components(separatedBy:" "))}
.map{($0,$1[1]+"\(Calendar.current.monthSymbols.index(of: $1[0])!+10)")}
.sorted{$0.1<$1.1}
.map{$0.0}

Compare date and pick next value from array in angular js

I have a json file with a list of holiday info, I would like to compare today's date with the list and display the next upcoming holiday.
How do I do the following?
Format today's date to compare with holiday json
Find the next holiday, display it's name and date
HTML display
<p>Next holiday is {{holiday.name}} on {{holiday.date}}</p>
Holiday Json
[
{
"name": "Christmas Eve",
"country": "US",
"date": "2015-12-24"
},
{
"name": "Christmas",
"country": "US",
"date": "2015-12-25"
},
{
"name": "First Day of Kwanzaa",
"country": "US",
"date": "2015-12-26"
},
{
"name": "Second Day of Kwanzaa",
"country": "US",
"date": "2015-12-27"
}
]
The other alternative is to use custom directive as below.
MyDirectives.directive("drHoliday", function() {
return {
replace: true,
restrict: 'A',
scope: false, //default
link: function(scope, element, attrs) {
items = scope.holidays.filter(function(item) {
var d1 = new Date();
var d2 = new Date(item.date);
return d2 > d1;
});
console.dir(items);
element.html('<p>Next holiday is ' + items[0].name + ' on ' + items[0].date + ' </p>');
}
}
});
And the markup would be something like below.
<div dr-holiday></div>
The working fiddle can be found here.
You can even sort filtered array by date if you are not taking care of same in server side code to make sure that items[0] would be the date you are expecting.
items.sort(function(a,b){
return new Date(b.date) - new Date(a.date);
});
Here is a function. Call it with your holidays array.
function getNextHoliday(holidays){
//Create date with today
var today = new Date();
//Iterate the holiday array in the scope
for (idx in holidays) {
//Create date variable for each holiday
var holiday = new Date(holidays[idx].date);
//Compare
if (holiday > today)
return holidays[idx].name + " on " + holidays[idx].date;
}
}
Here's a JSfiddle http://jsfiddle.net/user2314737/c6BfQ/277/
I used two filters: one to select dates greater than today's date and another to show only the first such item <tr ng:repeat="data in data | filter:dateFilter|limitTo:1">
function dateCtrl($scope) {
$scope.dateFilter = function ($scope) {
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var today = curr_year + "-" + curr_month + "-" + curr_date;
return (Date.parse($scope.date) > Date.parse(today));
}
$scope.data = [{
"name": "Christmas Eve Last Year",
"country": "US",
"date": "2014-12-24"
}, {
"name": "Christmas",
"country": "US",
"date": "2015-12-25"
}, {
"name": "First Day of Kwanzaa",
"country": "US",
"date": "2015-12-26"
}, {
"name": "Second Day of Kwanzaa",
"country": "US",
"date": "2015-12-27"
}];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng:app>
<div ng:controller="dateCtrl">What's the next holiday?
<table class="table">
<tr>
<th>name</th>
<th>country</th>
<th>date</th>
</tr>
<tr ng:repeat="data in data | filter:dateFilter|limitTo:1">
<td>{{data.name}}</td>
<td>{{data.country}}</td>
<td>{{data.date}}</td>
</tr>
</table>
</div>
</body>

How to pre load all locales into angular dynamic locale cache (tmhDynamicLocaleCache)

I am using angular dynamic locale (tmhDynamicLocale), but want all my locales to be pre loaded into the cache (tmhDynamicLocaleCache) when the app starts. The motivation behind this is to have all my resources bundled into 1 minified js file rather than the standard lazy loading. Is there a full example for this anywhere?
Solved it.
What i did was to put each locale into a module like so:
angular.module("myapp.locale.en", [
'tmh.dynamicLocale'
])
.run(['tmhDynamicLocaleCache', function (tmhDynamicLocaleCache) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
};
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
};
tmhDynamicLocaleCache.put('en', {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en",
"pluralCat": function (n, opt_precision) {
var i = n | 0;
var vf = getVF(n, opt_precision);
if (i == 1 && vf.v === 0) {
return PLURAL_CATEGORY.ONE;
}
return PLURAL_CATEGORY.OTHER;
}
});
}])
;
Create a module like this for each locale you use, just change "en" to "pt" or "he" etc (3 places in the code above).
Next load these modules into your app.js...
angular.module('myapp', [
'myapp.locale.en',
'myapp.locale.pt',
'myapp.locale.de',
'myapp.locale.he'
])
This way when .run() is called on each of these modules it will put the locale object into the tmhDynamicLocaleCache. Then when you later use tmhDynamicLocale.set('en') it will find the locale object in the cache and use it.

Resources