我有一个代码可以将任何日期(以秒为单位)转换为日期月份日期。这是:
var database = firebase.database();
database.ref(`trips/${userid}/trips/${tripid}/begindate`).once('value').then(photosSnap => {
var tripbegindateseconds = photosSnap.val();
var tripbegindatefull = new Date(0); // The 0 there is the key, which sets the date to the epoch
tripbegindatefull.setUTCSeconds(tripbegindateseconds);
var tripbeginmonth = tripbegindatefull.getUTCMonth() + 1; //months from 1-12
var tripbeginday = tripbegindatefull.getUTCDate();
var tripbeginyear = tripbegindatefull.getUTCFullYear();
tripbegindate = tripbeginday + "/" + tripbeginmonth + "/" + tripbeginyear;
$('#tripbegindate').html(tripbegindate);
});
我现在正试图将其实现为AngularJS代码。我正在从Firebase数据库中检索数据,并使用AngularJS显示它们。这是我检索数据的JS代码:
var app = angular.module('test', []);
app.controller('MainCtrl', function($scope) {
var database = firebase.database();
database.ref(`trips/${userid}/trips`).once('value')
.then(photosSnap => {
var trips = [];
photosSnap.forEach((trip) => {
trips.push({
tripKey: trip.key,
tripName: trip.val().name,
tripPhotoUrl: trip.val().photourl,
tripBeginDate: trip.val().begindate,
tripEndDate: trip.val().enddate
});
});
$scope.repeatData = trips;
// apply immediatly, otherwise doesn't see the changes
$scope.$apply();
// returns the array in the console to check values
console.log($scope);
}).catch(err => alert(err));
});
这里我的tripBeginDate和tripEndDate变量包含以秒为单位的日期。这些是我试图转换为日月份日期的变量。我不知道如何将我的代码实现到这个JS脚本中以使其工作。
答案 0 :(得分:1)
实际上你可以使用MomentJS和一些Angular包装器(例如,GitHub上的angular-moment)来执行任何日期操作。至少你会"跳过"维护和调试代码(关键字:时区有时会出现问题)。
答案 1 :(得分:0)
由于您拥有该功能的功能代码,只需将该代码包装到如下函数中:
function ConvertDate(DateInSeconds) {
var tripbegindateseconds = DateInSeconds;
var tripbegindatefull = new Date(0); // The 0 there is the key, which sets the date to the epoch
tripbegindatefull.setUTCSeconds(tripbegindateseconds);
var tripbeginmonth = tripbegindatefull.getUTCMonth() + 1; //months from 1-12
var tripbeginday = tripbegindatefull.getUTCDate();
var tripbeginyear = tripbegindatefull.getUTCFullYear();
tripbegindate = tripbeginday + "/" + tripbeginmonth + "/" + tripbeginyear;
return tripbegindate;
}
并在以下日期使用它:
tripBeginDate: this.ConvertDate(trip.val().begindate),
tripEndDate: this.ConvertDate(trip.val().enddate)
答案 2 :(得分:0)
你可以做到
var d=new Date(trip.val.begindate*1000) ;//time is in seconds,convert it to miliseconds
d.getMonth();//this will return you month in integer(e.g-january=0 and so on)
d.getFullYear();//this will return you year
d.getDate();//this will return you date
d.getDay();//this will return you day in integer like month
答案 3 :(得分:0)
我建议您使用片刻 - https://momentjs.com/我们可以解析任何日期格式,如下所示:
时刻(1454521239279).format(" DD MMM YYYY hh:mm a")//解析整数