我用swampdragon写了一个通知应用。不幸的是,pub_date变量包含了我不希望它存在的微秒数。我如何将其格式化为'dd-MM-yyyy HH:mm:ss'或像在管理网站(a. .下午版)?我的controller.js:
var AnnounceControllers = angular.module('AnnounceControllers', []);
AnnounceControllers.controller('AnnounceListCtrl', ['$scope', '$dragon', function ($scope, $dragon) {
$scope.announceList = {};
$scope.announcements = [];
$scope.channel = 'announce';
$dragon.onReady(function() {
$dragon.subscribe('announcements', $scope.channel, {announce_list__id: 1}).then(function(response) {
$scope.dataMapper = new DataMapper(response.data);
});
$dragon.getSingle('announce-list', {id:1}).then(function(response) {
$scope.announceList = response.data;
});
$dragon.getList('announcements', {list_id:1}).then(function(response) {
$scope.announcements = response.data;
});
});
$dragon.onChannelMessage(function(channels, message) {
if (indexOf.call(channels, $scope.channel) > -1) {
$scope.$apply(function() {
$scope.dataMapper.mapData($scope.announcements, message);
});
}
});
}]);
我app.js :
var AnnounceApp = angular.module('AnnounceApp', [
'SwampDragonServices',
'AnnounceControllers'
]);
在HTML中:
<h3 ng-repeat="item in announcements">
<div class="alert alert-info" role="alert">
{{ item.content }} {{item.pub_date| date:'dd-MM-yyyy HH:mm:ss'}}
<br>
</div>
</h3>
models.py:
pub_date = models.DateTimeField(auto_now_add = True)
serializers.py:
class AnnounceSerializer(ModelSerializer):
class Meta:
model = "post.Announce"
publish_fields = ("content","pub_date")
你必须将DateTimeField转换为ISO 8061格式,这样AngularJS的日期过滤器才能工作:
pub_date = models.DateTimeField(auto_now_add = True).isoformat(' ')
查看更多信息
编辑:进一步澄清后,问题是你得到的时间戳格式不正确,javascript无法将其识别为日期。
我使用了Daniel Cottone的一些信息,并做了这些:
class Announce(SelfPublishModel, models.Model):
serializer_class = AnnounceSerializer
announce_list = models.ForeignKey(AnnounceList)
content = models.CharField(max_length=100)
pub_date = models.DateTimeField(default=datetime.now)
date = models.TextField(null=True)
def __unicode__(self):
return self.content
@receiver(pre_save,sender=Announce)
def date_handler(sender,instance,*args,**kwargs):
instance.date = instance.pub_date.isoformat()
没有参数的isoformat对我有效。