backbone.js unix dates in underscore.js - backbone.js

I'm trying to get it right with my unix dates in an underscore js template.
In my template I have two unix dates coming from a backbone view that initialises this current template and passing the two dates as arguments.
In my template I now need to compare the two dates and get how many days it is between them. I cant do that in my view. I need to do it in the underscore template.
I'm using moment.js.
<% collection.each(function(model,index) { %>
<%
uploaded = moment(new Date(model.get("uploaded_date")))
servertime = moment(now) /*now is passed in as a variable since its not in the collection*/
%>
<p>
<%= uploaded.diff(servertime, 'days') %>
</p>
<% }); %>
I'm trying to use the diff() but all I get back is "0"
When I print the actual date variables I get the correct unix dates.
Anyone knows hows to do this?

I tried this code and it's working :
var uploaded = moment(new Date(1391185930000));
var servertime = moment(new Date(1390321930000)); // now at the date I wrote that example :)
alert(uploaded.diff(servertime, 'days'));
First try to add a ';' at the end of the two first lines of code.
What your 'now' variable looks like ? Have you tried this 'var servertime = moment();'

Related

Date validation using angular js

I have start date and end date picker in format of mm-dd-yyyy.End date should be with in 10 days range of start date and end date should not be before start date. How to validate using angular js.Any help is greatly appreciated
I advise you to use moment.js. Here's a basic tutorial and help to get started:
https://dzone.com/articles/getting-started-with-momentjs-intro-with-examples
Basically you would do:
function testDate(startDate, endDate){
var start = moment(startDate, 'mm-dd-yyyy');
var end = moment(endDate, 'mm-dd-yyyy');
if(endDate.isBefore(start)){
//start before end
}
if(startDate.add('days', 11).isAfter(endDate)){
//end not within 10 days range
}
//success!
}
It would be something like that. Hope it helps!
For simple pattern matching, you can use the ngPattern directive. For more complex validation (such as ensuring it's a valid date and within a certain range of another date), you will need to write your own validation directive or use the handy custom validation directive available from Angular-UI.
https://htmlpreview.github.io/?https://github.com/angular-ui/ui-validate/master/demo/index.html
Can you provide more details about this as in what library are you using for datepicker. It would help us answer.
Since you are using a datepicker you can restrict the date range in the fromDate field do not display any dates which are after a certain period (10 days from start date in you case).
jQuery datepicker allows this so does other datepickers.
EDIT:
In your controller do something like this.
var newDate = new Date($scope.startdate.getFullYear(), $scope.startdate.getMonth(), $scope.startdate.getDate()+10);
$scope.dateOptions = {
maxDate: newDate,
dateFormat: 'dd/mm/YYYY'
};
And now you can pass dateOptions to your input.
Note: Post a minimal plunkr for faster resolution of your issues.

Breeze/Angular: date input directive not working/strange behaviour

I'm trying to get this directive (https://github.com/eight04/angular-datetime) to work in my project. It works alright in the following plunk:
http://plnkr.co/edit/DawLbi?p=preview
But when I plug in the same code (below) into my larger scale project, it doesn't work and I have no idea why and where to search.
<input type="text" datetime="dd.MM.yyyy" ng-model="vm.firstDate" class="form-control" data-z-validate />
What happens: The input displays the formatted date correctly, but when I click on the year (or some other component) and try to change it using the number keys (enter a new year), it clears out the whole field (upon entering the first digit)! Using the up/down arrow keys works.
The problem happens only when I use the data-model on a breeze-entity. If I just put a simple js Date object on my controller and link to that one, it works.
I also tried extending my breeze entity like so:
function registerRechnungRec(metadataStore) {
metadataStore.registerEntityTypeCtor(g14EntityNames.rechnung, RechnungRec, postCtorInitializer);
function RechnungRec() {
this.datumExt = moment().toDate(); // doesn't work
}
function postCtorInitializer(rechnung) {
// this works, but not tracked by breeze then
rechnung.datumExtDate = moment(rechnung.datum).toDate();
}
// also no luck with that one:
// http://stackoverflow.com/questions/26982624/angular-and-breeze-edit-date-object
//addDateWrapperPropertyExt(RechnungRec, 'datum', 'datumExtDate');
}
A normal input with type date works just fine for entering/selecting the date. But I need to do some momentjs formatting afterwards to save the date correctly to the database then before I call entityManager.save(). Also, I don't really need the whole date picker component, a simple date input is all we need.
So how do I find out what's going wrong where?
Or is there another suggested date input directive/component, or an easier way to just have a text input field that allows me to input a date (no time) or a null date?

How to translate a date object using angular-translate?

I have a list of date in my view, powered by my controller. I am using angular-translate to manage localisation in my all application but do not know how to deal with date object.
My HTML looks like this :
<div ng-repeat="date in nextDates">
<div class="day">{{date | date: 'EEEE'}}</div>
</div>
This code display a list a day : Monday, Tuesday, ... based on date which is a date object.
My first try was to use moment.js which is already used in this project, and deal really well with i18n. It works, but I had a lot of difficulty to update it when lang is changed by user since moment.js is not related to angular-translate.
I tried to implement it on my controller using an event to update my variable but didn't worked well. I would like to keep the object date in my view instead of having a moment object, I am sure there is a way not implementing it manually.
$scope.$on('translationChanged', function(event, lang) {
...
});
I would like to know if there is an easy way to solve this issue, my only idea is to generate a key for translation like DAY.0 for Monday, DAY.1 and translate it by myself but it sounds cheap. moment.js seems perfect for the job, but then how to link it with angular-translate ?
Thanks for reading.
OK so after some research I found a library on github called angular-moment which work fine for me.
First I import both js files + locale
<script src="bower_components/moment/moment.js"></script>
<script src="bower_components/angular-moment/angular-moment.js"></script>
<script src="bower_components/moment/locale/fr.js"></script>
<script src="bower_components/moment/locale/de.js"></script>
<script src="bower_components/moment/locale/it.js"></script>
Then I set up momentjs locale variable during my app mode config
var core = angular.module('app.core').config(configLang);
configLang.$inject = ['moment'];
/* #ngInject */
function configLang(moment) {
moment.locale('en');
}
I then can start using in my templates amFormat directive directly on my Date object
<div ng-repeat="date in nextDates">
<div class="day">{{date | amDateFormat:'dddd'}}</div>
</div>
If I want to change language in my app, I just use moment.locale(String); and my view is automatically updated.
$rootScope.$on('$authenticationStateChanged', function(event, userData, isAuthenticated) {
moment.locale(userData.currentLanguage.toLowerCase());
});
$scope.$on('translationChanged', function(event, lang) {
moment.locale(lang.toLowerCase());
});
I can then access all the power of moment.js in my angular app :D.

AngularJS - trustAsHtml. Help Me Understand

I've been at this for too long.
Basically, I'm pulling information via json.
This works fine, but the information being pulled does not show up as HTML.
I've been trying to get trustAsHtml to work but I do not know what I'm doing wrong.
Here's my code:
Controller:
var pageControllers = angular.module('pageControllers', ['ngSanitize']);
pageControllers.controller('PackagesCtrl', function PackagesCtrl($scope, $sce, $http){
$http.get('scripts/all_packages.php').success(function(data){
$scope.packagesData = data;
});
});
I'm getting groups of data from the database fine. My data is rendering pure text instead of showing the actual html eg: <p class="myClass">My Returned Data</p>
My Html has an ng-repeat="item in packagesData"
and in that div I have:
ng-bind-html="item.more_info".
This returns the data I need, but how would I now make them render properly? Basically, from the returned fields, I need 2 results to show up as html, but everything I try does not work.
My json file returns multiple rows of data, e.g.:
[{"title":"My Title", "more_info":"<p>Information</p>"},{"title":"My Title 2", "more_info":"<p>Information 2</p>"}]
How do I target specific results such as "more_info" to show as html?
basically you right on your path. What you need to do is to check if its the right value with key. Key is you identifier for particular value.
The thing you need to do is to use an ng-if condition.
<h2 ng-if="key=='more_info'" ng-bind-html="value"></h2>

Getting data into an input field from YUI Calendar with multi-select:true

<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function(){
YAHOO.dateSelects.exc = new YAHOO.widget.Calendar("exc","excContainer",
{ title:"Choose a date:", close:true, multi_select:true });
YAHOO.dateSelects.exc.render();
YAHOO.util.Event.addListener(
"excshowup",
"click",
YAHOO.dateSelects.exc.show,
YAHOO.dateSelects.exc,
true
);
});
</script>
<div class="calendarOuterContainer">
<div id="excContainer" class="calendarContainer"></div>
</div>
<a id="excshowup"><img src="/images/icons/calendar.png" /></a>
The preceding code generates a YUI calendar with the ability to select multiple dates on one calendar. What I am having trouble figuring out is how to capture that data and place it inside a text input tag on the fly. So when a person clicks the close button, all the selected dates are populated inside the input tag.
Suggestions? (Code sample is greatly appreciated)
Subscribe to the hide event & call getSelectedDates() on your calendar instance which will return an array of JS Date objects. You can then format & combine those to get a string in the style you want to set the value of your text input.

Resources