将时间戳转换为日期格式

时间:2018-09-20 19:16:24

标签: angular typescript ionic-framework google-cloud-firestore

基本上,我要做的是将时间戳记格式化为显示可读的日期。目前,即时通讯收到这样的时间戳:

  

2018-10-10T05:00:00.000Z

我想做的是:2018-10-10 05:00 PM

这是我查询包含带有时间戳记的对象的文档的方式:

 ListarConsultas(){
    var query = firebase.firestore().collection("agendaMedicos")
    var auxint = 0;
    this.dataAux
    let auxString = '[';
    //db.collection('Agenda').where("Documento.id", "==", '1').get().then(res => {
    query.where('Deletado', '==', false).get().then(res => {
      res.forEach(item => {

        auxint++;
        auxString += '{"id":"' + item.id + '","agendaMedicos":' + JSON.stringify(item.data()) + '}';
        console.log(item);
        if (res.size != auxint)
          auxString += ', ';
      })
      auxString += ']';
      this.dataJSON = JSON.parse(auxString);
      console.log(auxString);

      console.log(this.dataJSON);
    }).catch(err => {
      console.log('Ocorreu um erro ' + err);
    });
  }

我如何在HTML上显示它

<ion-content padding>
    <div padding-top class="card" *ngFor="let data of dataJSON">
        <div class="card__consulta avaliar">
            <div class="card__consulta--header">
                <h3>Consulta em cardiologia - {{data?.agendaMedicos?.Documento?.Especialidade}}</h3>
                <span>Cardiologia</span>
            </div>
            <div class="card__consulta--content">
                <span>Atendimento realizado em: {{data.agendaMedicos.Documento.HoraFim}}</span>
            </div>
            <ion-row align-items-center class="card__consulta--footer">
                <ion-col>
                    <span>Código de confirmação:</span>
                    <strong>99887</strong>
                </ion-col>
                <ion-col col-5 center text-center>
                    <button class="btn btn-outline-secondary">
                        Avaliar
                    </button>
                </ion-col>
            </ion-row>
        </div>
    </div>
</ion-content>

1 个答案:

答案 0 :(得分:1)

希望此解决方案对您有用。我认为这里定义的许多方法几乎就像重新发明轮子一样,因为我知道库可能只是根据格式化字符串来格式化日期。

//dateString will take values like '2018-10-10T23:00:00.000Z'
function computeDateString(dateString) {
    var input = new Date(Date.parse(dateString))
    var padder = function (val) {
        return pad(val)
    }
    var time = [format12Hour(input.getHours()), input.getMinutes(), input.getSeconds()].map(padder).join(':')
    var date = [input.getMonth(), input.getDate(), input.getFullYear()].map(padder).join('-')
    return [date, time, getAMPM(input.getHours())].join(' ')
}

function pad(val) {
    return (val < 10) ? '0' + val : val
}

function format12Hour(val) {
    var val = (val+1) > 12 ? val-12:val
    return val === 0? 12:val
}

function getAMPM(val) {
    return val > 12 ? 'PM':'AM'
}
//prints 09-10-2018 10:30:00 AM
console.log(computeDateString('2018-10-10T23:00:00.000Z'))

希望这会有所帮助。