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,
Related
I am using v-calendar as a date picker in my Vue project. My objective is to select complete week - 7 days fixed from sunday to saturday. I have been looking around in the documentation but unable to get my head around it.
This is what I have as an example
https://codepen.io/achaphiv/pen/OJXjooB
<div id='app'>
<v-date-picker v-model="value" :available-dates="availableDates" is-inline></v-date-picker>
The current date is: {{ value || 'null' }}
</div>
new Vue({
el: '#app',
data() {
const now = new Date()
const later = new Date(now.getTime() + 5 * 60 * 1000)
return {
value: null,
availableDates: [
{ start: now, end: later }
]
}
}
})
If I understood you correctly try like following snippet:
new Vue({
el: '#app',
data() {
return {
value: null,
availableDates: {
start: new Date(),
end: new Date(new Date().setDate(new Date().getDate() + 7))
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/v-calendar#1.0"></script>
<div id='app'>
<v-date-picker v-model="value" :available-dates="availableDates" is-inline></v-date-picker>
The current date is: {{ value || 'null' }}
</div>
I want to calculate the earnings from share using vue. I'm subtracting the day closing amount to the start one. I'm not able to display the result on the Dom.
JSfiddle: https://jsfiddle.net/4bep87sf/
This is the code:
let app = new Vue({
el: '#app',
data: {
s: '',
e: '',
tot: '0'
},
watch: {
e: function(){
this.tot = (this.e + this.s);
return this.f;
}
});
Use a computed property:
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => ({
s: 0,
e: 0
}),
computed: {
tot() {
return Number(this.s) + Number(this.e);
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input v-model="s" type="number">
<input v-model="e" type="number">
<pre>{{s}} + {{e}} = {{tot}}</pre>
</div>
Also note you need to cast your values as Number() if you want the sum to be correct. If they're interpreted as strings a + b = ab.
Very close to tao answer. Only "fix" two User experience issues (Not directly related to Vue).
Issue 1: "030" or "30" ahhhh:
First, if you set a default value (0 for example), when the user focuses input and type "3" the output is 03! (or 30) ==> Very annoying (Especially on mobile).
Sometimes it's better to set the input value to null and show input placeholder (Fix this annoying issue).
Issue 2 (No meaning result):
The output 0 + 0 = 0 does not contribute too much to the user. Sometimes it's better to put the sum inside v-if.
<p v-if="number1 && number2">{{total}}</p>
Basic code example
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => ({
number1: {
type: Number,
value: null,
placeholder: "Enter number 1",
},
number2: {
type: Number,
value: null,
placeholder: "Enter number 2",
}
}),
computed: {
total() {
return Number(this.number1.value) + Number(this.number2.value);
}
},
})
span{
color: red;
font-weight: bold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h3></h3>
<div>
<label>Number 1:</label>
<input autofocus v-model="number1.value" type="number" v-bind:placeholder="number1.placeholder">
</div>
<div>
<label>Number 2:</label>
<input v-model="number2.value" type="number" v-bind:placeholder="number2.placeholder">
</div>
<p>Total:<span v-if="number1.value && number2.value"> {{total}}</span></p>
</div>
v-model.lazy also sometimes useful for calucations:
By default, v-model syncs the input with the data after each input
event (with the exception of IME composition, as stated above). You
can add the lazy modifier to instead sync after change events. https://v2.vuejs.org/v2/guide/forms.html#lazy
Rather beginner question, but I couldn't find a solution anywhere.
I have 2 buttons that increment/decrement a given Date object by +/- 1 day. The object is updated, but the changes are not displayed. I found out it's because the Date Obj is not reactive, but I didn't find a solution or a workaround to this.
JSFiddle Demo
HTML:
<div id="app">
<button #click="inc">+ 1 day</button>
<button #click="dec">- 1 day</button>
<br /><br />
{{date}}
</div>
JS/Vue:
new Vue({
el: "#app",
data: {
date: new Date()
},
methods: {
inc () {
this.date.setDate(this.date.getDate() + 1)
console.log(this.date)
},
dec () {
this.date.setDate(this.date.getDate() - 1)
console.log(this.date)
}
}
})
In the console the Date is incresed/decreased fine, but the date rendered on the page just stays the same. Can anybody help with this? Thanks.
You are modifying the date object in place in which case Vue can not detect the changes, create a new date object instead:
https://jsfiddle.net/13gzu8xs/1/
new Vue({
el: "#app",
data: {
date: new Date()
},
methods: {
inc () {
this.date.setDate(this.date.getDate() + 1)
this.date = new Date(this.date) // create a new date and assign to this.date
},
dec () {
this.date.setDate(this.date.getDate() - 1)
this.date = new Date(this.date)
}
}
})
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
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>