Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

javascript - How to get date and time in Angular 4,5,6 and above using DatePipe

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Will works on Angular 6 or above

You don't need any 3rd party library. You can format using angular method/util. import formatDate from the common package and pass other data. See the 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...