将以秒为单位的日期转换为 'day month year' 日期

Transforming date which is in seconds to a 'day month year' date

我有一个代码可以将任何以秒为单位的日期转换为日月年日期。这是:

    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 脚本中以使其工作。

因为你有功能的函数代码,只需将该代码包装成这样的函数:

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)

事实上,您可以使用 MomentJS 和一些 Angular 包装器(例如 angular-moment on GitHub)来对日期进行任何操作。至少你会 "skip" 维护和调试你的代码(关键词:时区有时是有问题的)。

你可以做到

      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

我建议您使用 moment-https://momentjs.com/,我们可以在其中解析任何日期格式,如下所示:

moment(1454521239279).format("DD MMM YYYY hh:mm a") //解析整数