2

Below is my code. using angular 2 build in date pipe to convert time stamp to proper date format.

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template:`<h1>My First Angular 2 App</h1>
<p>{{test | date: 'dd/MM/yyyy'}} - format: dd/MM/yyyy</p>`
})

export class AppComponent { 
test : Date = '2017-04-30T23:59:59';
}

Output: 01/05/2017 - format: dd/MM/yyyy

but i'm expecting 30/04/2017 as my ooutput

Ireal
  • 355
  • 4
  • 16

3 Answers3

3

If you want to display only date use this

<div>{{test.split("T")[0] | date : 'dd/MM/yyyy'}}</div>
byteC0de
  • 5,153
  • 5
  • 33
  • 66
0

My solution works as below

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2><br>
      <h5>{{test | date: 'dd/MM/yyyy'}}</h5>
    </div>
  `,
})
export class App {
  name:string;
   test : Date = new Date('2017-04-30T23:59:59');
  constructor() {
    this.name = `Angular! v${VERSION.full}`;
   console.log(this.test)
  }
}

LIVE DEMO

Update :

 getExcatDate(string){
    let year=new Date(this.name).getYear();
    let month=new Date(this.name).getMonth();
    let date=new Date(this.name).getDate();

    let local= (date.toString().length===1 ?  '0' +date : date) + '/' +
                (month.toString().length===1 ?  '0' +month : month) 
              + '/' +  year.toString().substring(1);
    console.log(local)
    return local;
  }

Use the above method to get the exact date as Pankaj said Date pipe will not work for your case. demo is updated

Aravind
  • 40,391
  • 16
  • 91
  • 110
0

I think you are running into a time zone issue.

From https://www.w3schools.com/js/js_dates.asp:

When setting a date, without specifying the time zone, JavaScript will use the browser's time zone.

When getting a date, without specifying the time zone, the result is converted to the browser's time zone.

When I tested just creating a date with your string in the constructor in jsFiddle and console logged it out, I was getting a time 5 hours later than what I defined, which would correspond to GMT.

Try setting the date with a timezone specified:

test : Date = new Date('2017-04-30T23:59:59Z');
Adam
  • 2,446
  • 1
  • 13
  • 16