Format date in AngularJS is not working - javascript

In my project the data is coming to front-end as a json object as shown below:
{
id: 1,
meetingName: "Meeting 1",
meetingDate: "2018-02-21",
startTime: "10:00:00"
}
<td>{{meeting.startTime|date:"h:mma"}}</td>
I used the above method to format the date in angularjs code as 10:00 AM.
But the start time is still shown as 10:00:00. Why is it not formatting the date according to the format?

date filter expects a date object as input. But you are passing a string. Below is a sample code that show the date as expected.
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope) {
let info = {
id: 1,
meetingName: "Meeting 1",
meetingDate: "2018-02-21",
startTime: "10:00:00"
}
$scope.meetingDate= new Date(info.meetingDate + " " + info.startTime);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="datCtrl">
<p>Meeting Time= {{ meetingDate | date:"h:mma" }}</p>
</div>
</body>
Date Filter Docs
Hope this helps :)

Filter date expects an object of type date. This custom filter could help you:
View
<div ng-controller="MyCtrl">
{{data.startTime|timeFilter: data.meetingDate: 'h:mma'}}
{{data.startTime|timeFilter: data.meetingDate: 'yyyy-MM-dd HH:mm:ss Z'}}
</div>
AngularJS application
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.data = {
id: 1,
meetingName: "Meeting 1",
meetingDate: "2018-02-21",
startTime: "10:00:00"
};
});
myApp.filter('timeFilter', function ($filter) {
return function (data, aDate, dateFilter) {
return $filter('date')(new Date(aDate + " " + data), dateFilter);
}
})
> Demo fiddle

Related

Angular js solve a different format of a json array of objects

Based on the result below , how can an angular for each loop be able to solve that json array of objects format ? The value is title and the id is key. Any Idea? Thank you.
mycode
me.record.questionaires = []
angular.forEach(detail.questionaires, function (value, key) {
me.record.questionaires.push({ "id": key, "title": value })
});
Formated json data (detail.questionaire result)
[
"{'sub_title': 'dsadsa', 'instruction': 'You Must',…elimit': '01:05:19', 'title': 'asdsa', 'id': 133}",
"{'sub_title': 'sdasdsa', 'instruction': None, 'cre…melimit': '05:30:09', 'title': 'asda', 'id': 131}"
]
You need to
Loop over the array
Parse the string as JSON
Push or map the appropriate values into your questionaires array (it's not clear what data you want)
me.record.questionaires = detail.questionaires.map(json => {
let { id, title } = JSON.parse(json)
return { id, title }
})
I had to change your sample formatted JSON a bit because it was giving me console errors. Please see if this helps.
angular
.module("myModule", [])
.controller("myController", function($scope) {
var me ={record: {questionaires: []}};
$scope.me = me;
var detail ={};
detail.questionaires = [
"{'sub_title': 'dsadsa', 'instruction': 'You Must','…elimit': '01:05:19', 'title': 'asdsa', id: 133}",
'{"sub_title": "sdasdsa", "instruction": "None", "cre…melimit": "05:30:09", "title": "asda", "id": 131}'
];
angular.forEach(detail.questionaires, function (value, key) {
var questionaire = JSON.parse(value.replace(/'/g, '"').replace(/id:/g, '"id":'));
me.record.questionaires.push({ "id": questionaire.id, "title": questionaire.title });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myModule">
<div ng-controller="myController">
<div><strong>me.record.questionaires:</strong></div>
<div ng-repeat="q in me.record.questionaires">
<div>{{q}}</div>
</div>
</div>
</div>

Include Variable value in date pipe in Kendo (Dynamic format) : AngularJS

I have a Kendo Column for date value, There we have used a pipe like this at template property inside the below column.
Now i want to change the format of kendo grid column according to the date format
My Problem/Question :- I am retrieving Date format such as dd-MM-yyyy or MM-dd-yyyy or dd-MM-yy or MM-dd-yy from localStorage which is dynamic according to the user preference.
But whenever i use that variable in the template (containing date format ex: dd-MM-yyyy) in place of the default date pipe having same format of default date pipe, kendo Do not accept it and gives the error : Cannot read property 'timeout' of undefined kendo
const myDateFormat = this.$localStorage.dateFormat;
function getDefaultColumns($translate) {
return [
{
field: 'INVOICE_DATE',
title: $translate.instant('invoiceDate'),
headerTemplate: '{{ \'invDate\' | translate }}',
template: '{{ dataItem.INVOICE_DATE | date: \'yyyy-MM-dd\' }}',//i am using the localStorage value here
filterable: {
ui(element) {
element.kendoDatePicker({
format: 'yyyy-MM-dd'
});
}
},
width: 100
}
];
}
I think you can accomplish what you want with a ES2015 Template String.
Consider this modification to your program listing:
function getDefaultColumns($translate) {
let dateFormat = 'yyyy-MM-dd';
return [
{
field: 'INVOICE_DATE',
title: $translate.instant('invoiceDate'),
headerTemplate: '{{ \'invDate\' | translate }}',
template: `{{ dataItem.INVOICE_DATE | date: \'${dateFormat}\' }}`,
filterable: {
ui(element) {
element.kendoDatePicker({
format: dateFormat
});
}
},
width: 100
}
];
}

How to format a (possibly null/empty) date in VueJS

Using Vue.JS 1.0, I couldn't find a simple way to properly format a JSON date that can be empty.
I tried with vue-filter npm package date filter but it fails if the date is empty. For example if my data is:
{ name: "John", birthday: null }, /* unknown birthday */
{ name: "Maria", birthday: "2012-04-23T18:25:43.511Z" },
returns
John 12/31/1969 9:00:00 PM <-- null date should be blank
Maria 4/23/2012 3:25:43 PM <-- ok
The code i am using:
<!DOCTYPE html><html>
<head>
<script src="lib/vue/dist/vue.min.js"></script>
<script src="lib/vue-filter/dist/vue-filter.min.js"></script>
</head>
<body>
<div id="app">
<h1>Without Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday}}</div>
</div>
<h1>With Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday | date }}</div>
</div>
</div>
<script>
new Vue({
el: "#app",
data: {
list: [
{ name: "John", birthday: null },
{ name: "Maria", birthday: "2012-04-23T18:25:43.511Z" },
]
}
});
</script>
</body>
</html>
What is the proper way to format a date, that will also make show blank if date is null?
Write a custom filter to wrap the date filter. If the input is null, return null, otherwise return Vue.filter('date')(input)
Vue.filter('dateOrNull', function(d, ...others) {
return d ? Vue.filter('date')(d, ...others) : null;
});
new Vue({
el: "#app",
data: {
list: [{
name: "John",
birthday: null
}, {
name: "Maria",
birthday: "2012-04-23T18:25:43.511Z"
}, ]
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<script src="//rawgit.com/wy-ei/vue-filter/master/dist/vue-filter.min.js"></script>
<div id="app">
<h1>Without Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday}}</div>
</div>
<h1>With Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday | dateOrNull '%B'}}</div>
</div>
</div>
It doesn't work well:
Roy answers exactly what I asked. But it turned out that vue-filter was not good for my needs. I needed '%c' to show date in browser's locale format (bad idea). vue-filter source was actually doing the following: (rewrited as a stand alone filter, to avoid the dependency):
Vue.filter('date', function (d) {
var date = new Date(d);
return d ? date.toLocaleDateString() + ' ' + date.toLocaleTimeString().trim() : null;
});
It is terrible: each browser works differently. And dates with unknown timezone are assumed UTC and moved to local timezone causing this when living at GMT-3:
New plan:
Use Moment.js with a custom filter:
Vue.filter('moment', function (date) {
var d = moment(date);
if (!d.isValid(date)) return null;
return d.format.apply(d, [].slice.call(arguments, 1));
});
Don't forget <script src='moment.js'>.
Usage: {{ date | moment "dddd, MMMM Do YYYY" }}
See also: Moment Date and Time Format Strings
I also tried vue-moment npm package BUT it depends on CommonJS / require() syntax, and I don't want to use webpack/browserify just for this,

set ng-model value as the div text

I want to display a list of records. The data is a list of objects, each object is like this:
{
date: "01/01/2001",
time: "04:28 AM",
message: "message strings here."
}
I want to display them in the way that grouped by date. Like this:
08/01/2005
04:28 AM message strings here.
04:20 AM message strings here.
02:12 AM message strings here.
07/05/2005
03:32 PM message strings here.
02:12 PM message strings here.
This is my code:
<div>{{date}}</div> <!--date is initialized in my angular controller to be the first date in the records.-->
<div ng-repeat="record in records">
<div ng-if="record.date != date" ng-model="date">{{record.date}}</div> <!--here I expect date would be updated to record.date.-->
<div>{{record.time}} {{record.message}}</div>
</div>
But I get result like this:
08/01/2005
04:28 AM message strings here.
04:20 AM message strings here.
02:12 AM message strings here.
07/05/2005
03:32 PM message strings here.
07/05/2005 //This is displayed, means the date is not updated when it reach the first 07/05/2005 above.
02:12 PM message strings here.
I searched online, a lot of model data binding is to bind model with <input>. But I don't want input tag. And the ng-model in <div> seems doesn't update the model to the text displayed in the <div>. I wonder what's the proper way to achieve this.
I setup an example based on your data on how to do that: https://jsfiddle.net/63o96cf2/
Original answer: https://stackoverflow.com/a/14800865/3298029
View:
<div ng-app ng-controller="Main">
<ul ng-repeat="group in recordsToFilter() | filter:filterRecords">
<b>{{group.date}}</b>
<li ng-repeat="record in records | filter:{date: group.date}">{{record.time}}: {{record.message}}</li>
</ul>
</div>
Controller:
function Main($scope) {
$scope.records = [{
date: "01/01/2001",
time: "03:28 AM",
message: "message strings here."
}, {
date: "01/01/2001",
time: "04:28 AM",
message: "message strings here."
}, {
date: "01/01/2001",
time: "06:28 AM",
message: "message strings here."
}, {
date: "01/01/2002",
time: "04:28 AM",
message: "message strings here."
}, {
date: "01/01/2002",
time: "05:28 AM",
message: "message strings here."
}];
var indexedRecords = [];
$scope.recordsToFilter = function() {
indexedRecords = [];
return $scope.records;
}
$scope.filterRecords = function(record) {
var recordIsNew = indexedRecords.indexOf(record.date) == -1;
if (recordIsNew) {
indexedRecords.push(record.date);
}
return recordIsNew;
}
}
You need to use "groupBy" filter in https://github.com/a8m/angular-filter#groupby
HTML
<ul ng-repeat="record in records | groupBy:'date'">
{{ record.date }}
<li ng-repeat="player in value">
{{ record.time }} ...
</li>
</ul>

AngularJS - Currency filter with a custom filter not working

I have a very simple thing I want to do. I want to add a currency filter to the custom filter I wrote.
Here is it:
var app = angular.module('testapp', []);
app.controller('MainCtrl', function() {
this.people = [{
name: 'James',
bank: 5285
}, {
name: 'Mary',
bank: 849
}];
});
app.filter('richmeter', function() {
return function(bank) {
if (bank > 2500) {
return bank + ' [RICH]'
} else {
return bank;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testapp">
<div ng-controller="MainCtrl as vm">
<div ng-repeat="people in vm.people | filter:richmeter">
{{people.name}} has {{people.bank | currency }}
</div>
</div>
</div>
Why is this not working? What am I doing wrong?
Thank you.
The AngularJS currency filter expects the required amount parameter to be a number. Within your richmeter filter you appear to be conditionally returning a string, which means that people.bank will not function as expected within the currency filter.

Categories

Resources