How to get date and time in Angular 4 using DatePipe

ぐ巨炮叔叔 提交于 2020-01-12 07:40:13

问题


I am working in an angular 4 application ,Here I need to get the current Date and Time Using angular DatePipe.

I want to get the date and time in the following format

dd-mm-yyyy hh:MM:ss AM/PM

I got the expected by using the Angular DatePipe as follows

<p>{{today | date:'dd-MM-yyyy hh:mm:ss a':'+0530'}}</p> 

output :

10-05-2018 03:28:57 PM

Here I What I want to do is get the same output from my app.component.ts without touching the HTML's

So I tried the below code but it generates a 13 digit timestamp

today = Date.now();
    fixedTimezone = this.today;

SO how can I get the date and time as the mentioned format purely from app.component.ts file without using HTML's.


回答1:


let dateFormat = require('dateformat');
let now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

Thursday, May 10th, 2018, 7:11:21 AM 

And this format is exactly like your question

dateFormat(now, "dd, mm, yyyy, h:MM:ss TT"); 

returns 10, 05, 2018 7:26:57 PM

you need npm package npm i dateformat here is a link for the npm package https://www.npmjs.com/package/dateformat

Here is another question that inspires me How to format a JavaScript date


h:MM:ss TT results 7:26:57 PM

HH:MM:ss results 13:26:57

Here is it https://jsfiddle.net/5z1tLspw/

I hope that helps.




回答2:


Will works on Angular 6 or above

You don't need any library. If you can do it with angular. import formatDate from common package and pass other data. See below given example.

import { Component } from '@angular/core';
import {formatDate } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  today= new Date();
  jstoday = '';
  constructor() {
    this.jstoday = formatDate(this.today, 'dd-MM-yyyy hh:mm:ss a', 'en-US', '+0530');
  }
}

stackblitz: https://stackblitz.com/edit/angular-vjosat?file=src%2Fapp%2Fapp.component.ts




回答3:


Uses the function formatDate to format a date according to locale rules.

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

It may be useful:)



来源:https://stackoverflow.com/questions/50270330/how-to-get-date-and-time-in-angular-4-using-datepipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!