Get date to display just month and year AngularJS, Firebase - angularjs

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

Related

Jquery datepicker button is not working well

I am using datepicker for my view. I also use angularjs. The problem is that when i use ok button it doesnt not change ng-model state. it still shows ng-empty. I use this value to calculate for another field, you can ignore that.
Just tell how can imake ok button active instead of onClose? I need to make sure the ng-model change when user select a month and year.
My date picker:
$(function () {
$('.date-picker').datepicker({
yearRange: "-5:+0",
showButtonPanel: true,
dateFormat: 'MM yy',
changeMonth: true,
changeYear: true,
closeText: 'OK',
beforeShow: function () {
$(this).datepicker('widget').addClass('hide-calendar');
if ((selDate = $(this).val()).length > 0) {
iYear = selDate.substring(selDate.length - 4, selDate.length);
iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
}
},
onClose: function (dateText, inst) {
$(this).datepicker('widget').removeClass('hide-calendar');
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var mN = $("#monthNo").val();
if (mN == '') {
return;
}
var tm = parseInt(month) + parseInt(mN-1)
if (tm > 11) {
tm = tm - 12;
year =parseInt(year) + 1;
}
$("#to").val(monthNames[parseInt(tm)] + " " + year);
}
}).click(function () {
$('.ui-datepicker-calendar').hide();
}).attr("readonly", true);
});
$scope.$apply() is redundant. try $scope.$digest(). but remember jquery plugins always have lots of problems in angular/ try to use angular plugins/ it save you a lot of time in the future

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

Angular -- ng-init scope variable not passing into view

I have the following in my index.html
<header>
<select ng-model="date.month" ng-init="currentMonth" ng-options="month for month in months">
</select>
<select ng-model="date.year" ng-init="date.year" ng-options="year for year in years">
</select>
</header>
I have the following in my app.js
.controller('MainCtrl', function ($scope) {
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
$scope.date = {
year: year,
month: month
};
$scope.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
$scope.currentMonth = $scope.months[month - 1];
var years = [];
var earliestYear = year - 100;
for (var i = earliestYear; i <= year; i++) {
years.push(i);
}
$scope.years = years;
$scope.$watchCollection('date', function (date) {
$scope.currentDate = new Date(date.year, date.month, 1);
});
My ng-init for "date.year" works, but not for "currentMonth". However, I know currentMonth is connected to the view. Why isn't ng-init recognizing ng-init="currentMonth"?
ng-init is an expression so you need to assign currentMonth to your date.month model.
<select ng-model="date.month" ng-init="date.month=currentMonth" ng-options="month for month in months">
</select>
The ng-init="date.year" doesn't actually do anything. The date.year model has already been assigned 2016 so it looks like it works.
See plunker

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!

how to pass variable values to controller

<div id="dsel1" style="text-align:center;width:800px;"></div><br>
<br>
<span id="wtf"></span>
<script type="text/javascript">
var calendarPicker1 = $("#dsel1").calendarPicker({
monthNames:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
callback:function(cal) {
var date=cal.currentDate;
alert(date);
$("#wtf").html("Selected date: " + cal.currentDate);
}});
</script>
here this code displays date from datepicker , it works fine but i have to pass the date variable value to profiles controller, index action with this one id and the date cariable
// javascript redirect
window.location = '/profiles/index?id=123&date=2014-05-03'
// ProfilesController
public function index() {
$id = $this->request->query['id'];
$date = $this->request->query['date'];
}
OR if you want to stay on the same page use ajax
$.ajax({
url:'/profiles/index',
data:{id:123, date:'2014-05-03'},
type:'POST',
success:function(data, textStatus, jqXHR) {
// do something
}
})
// ProfilesController
public function index() {
if($this->request->is('ajax')) {
$id = $this->request->data['id'];
$date = $this->request->data['date'];
// do something
}
}

Resources