42

I'm using Angular 2.0 final, and I have an incorrect format of dates when I add hours and minutes in the format string:

In the template of the component, I have:

<th id="lastexecution">{{dto.LastExecution | date:'yyyy-MM-dd HH:mm:ss'}}</th>

The output date in IE 11 is:

2016-09-27 15:00:9/27/2016 3:53:46 PM:9/27/2016 3:53:46 PM

With {{dto.LastExecution | date:'yyyy-MM-dd'}}

The output date in IE 11 is correct:

2016-09-27

Here is the components version I use in the package.json:

{
  "name": "ima_sentinel",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "docker-build": "docker build -t ima_sentinel .",
    "docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ima_sentinel",
    "pree2e": "npm run webdriver:update",
    "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
    "lint": "tslint ./app/**/*.ts -t verbose",
    "lite": "lite-server",
    "postinstall": "typings install",
    "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
    "test-once": "tsc && karma start karma.conf.js --single-run",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings",
    "webdriver:update": "webdriver-manager update"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.1",
    "linqts": "^1.6.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "signalr": "^2.2.1",
    "systemjs": "0.19.27",
    "typescript-collections": "^1.1.9",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "concurrently": "^2.2.0",
    "lite-server": "^2.2.0",
    "typescript": "^2.0.2",
    "typings": "^1.0.4",
    "canonical-path": "0.0.2",
    "http-server": "^0.9.0",
    "tslint": "^3.7.4",
    "lodash": "^4.11.1",
    "jasmine-core": "~2.4.1",
    "karma": "^1.2.0",
    "karma-chrome-launcher": "^0.2.3",
    "karma-cli": "^0.1.2",
    "karma-htmlfile-reporter": "^0.2.2",
    "karma-jasmine": "^0.3.8",
    "protractor": "^3.3.0",
    "rimraf": "^2.5.2"
  },
  "repository": {}
}
Anthony Brenelière
  • 60,646
  • 14
  • 46
  • 58

8 Answers8

62

UPDATE - The Angular issue that causes this issue is resolved in Angular 5. If you can, I would recommend using that to avoid this problem.

If you are still using Angular 4 or older - as a workaround, I created a pipe to use the moment formatter instead of the Angular built-in one:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
    name: 'datex'
})

export class DatexPipe implements PipeTransform {
    transform(value: any, format: string = ""): string {
        // Try and parse the passed value.
        var momentDate = moment(value);

        // If moment didn't understand the value, return it unformatted.
        if (!momentDate.isValid()) return value;

        // Otherwise, return the date formatted as requested.
        return momentDate.format(format);
    }
}

Which can then be used:

{{exampleDate | datex:'DD/MM/YYYY HH:mm:ss'}}

The date you pass in should be something which moment can parse (see the relevant moment documentation) and the format string is a moment, not angular, date formatting string, as documented here.

I've tested this in IE11, Chrome and Firefox and it behaves consistently.

You'll need to ensure moment is added to your package.json as a dependency, e.g.:

{
  "name": "demo",
  "version": "0.0.1",
  // snip
  "dependencies": {
    // snip
    "moment": "^2.15.1",
    // snip
  },
  "devDependencies": {
    //snip
  }
}

... and ensure your systemjs.config.js is updated so it can locate moment:

map: { 
  'moment': 'npm:moment' 
} 
packages: { 
  moment: { main: './moment.js', defaultExtension: 'js' } 
}
Mark Hughes
  • 7,264
  • 1
  • 33
  • 37
  • It results with the following error when executing the project: XHR error (404 Not Found) loading http://localhost:3000/moment. I have no idea why it is looking for the the library at this place whereas it is located in node_modules/moment. I have no error at compile time. – Anthony Brenelière Oct 21 '16 at 09:13
  • Ok system.config.js was not updated by the package install. I had to add: map: { 'moment': 'npm:moment' } packages: { moment: { main: './moment.js', defaultExtension: 'js' } } It works pretty well thank you!!! – Anthony Brenelière Oct 21 '16 at 09:48
  • It just gives another form of garbage as a result. 01/th/y for MM/dd/y. – Léon Pelletier Jan 12 '17 at 22:12
  • @léon-pelletier I'm not sure that is a valid momentjs format string for what you're trying to achieve (e.g. dd in moment formats as a two-letter day of week abbreviation); check the momentjs documentation linked in the answer for valid moment format strings. – Mark Hughes Jan 12 '17 at 22:20
  • 2
    What I've done is to rewrite my formats to work with this pipe and momentjs. Working very well now. +1! – Léon Pelletier Jan 13 '17 at 04:30
  • Updated following on from the comment-answer from @seven – Mark Hughes Apr 25 '17 at 14:36
  • 1
    ***Tip:** If anyone wants to add moment in app.module.ts, it's like this: `import { Moment } from 'moment';` – Sam Jun 02 '17 at 04:45
  • 1
    You should not use this anymore if you use Angular 5, where the problem with native date pipe is solved. Note, that adding moment.js adds more than 300Kb in parsed size to the production build (in Angular 5 and CLI 1.6.8). – Ondrej Peterka Feb 14 '18 at 14:24
  • 1
    Great point @OndraPeterka - I've updated the answer to make it clear that using Angular 5 is the best way to fix this issue :) – Mark Hughes Feb 14 '18 at 14:42
15

From Angular2 DatePipe API Documentation.

"this pipe uses the Internationalization API. Therefore it is only reliable in Chrome and Opera browsers.

Omri L
  • 739
  • 4
  • 12
10

If you are okay with showing AM/PM instead of 24 hour time, another valid workaround is to break the formatting into two, and use shortTime or mediumTime for displaying the time portion:

{{dto.LastExecution | date:'yyyy-MM-dd'}} {{dto.LastExecution | date:'shortTime'}}

This should work in all major browsers, including IE and Edge.

Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102
5

Regarding the answer from @mark-hughes above, from the moment API documentation:

date_expression | date[:format]

expression is a date object or a number (milliseconds since UTC epoch) or an ISO string

Reference

So the value should be any type, and you can use moment().isValid() to check the value type

@Pipe({name: 'datex'})
export class DatexPipe implements PipeTransform {
    transform(value: any, format: string = ""): string {
       return moment(value).isValid()? moment(value).format(format) : value; 
    }
}
Mark Hughes
  • 7,264
  • 1
  • 33
  • 37
Seven
  • 843
  • 8
  • 10
2

Work in Angular 5.x

In version 5.x of the Angular this problem is working correctly in Edge (v.38.14393.1066.0) and in IE (v.11.1198.14393.0), test in your version!

Live example: Plunker Angular 5.x


Related issue that solved the problem (if I found something inconsistent): https://github.com/angular/angular/issues/9524


Answer that involves the entire operation of the Angular DatePipe.

Fernando Leal
  • 9,875
  • 4
  • 24
  • 46
  • Hello i tried the link you gave for Plunker and is not working on IE 11. Is this related to the DatePipe issue? – apoellitsi Jun 25 '18 at 14:24
2

The below solution works fine in for IE11 and chrome. No need to create custom pipes.

 {{dto.createdTimeLocal | date:'dd MMM yyyy'}} {{dto.createdTimeLocal | date:'shortTime'}}
Muni Chittem
  • 988
  • 9
  • 17
0

moment.js pipes for Angular

Marks answer is great and it was what I was using till I found this simple solution that is well documented.

moment.js pipes for Angular

This module works with Angular 2.0 and above.

JCPhlux
  • 455
  • 5
  • 9
0

No need to write format like this {{date:dd/MM/yyyy hh:mm:ss a}}.
IE11 or EDGE getting issue with this format only.

Here are some alternatives:

Ex 1: new date and time:

var date = new Date().toLocaleDateString();
var time = new Date().toLocaleTimeString();

var datetime = date + " " + time;

Ex 2: Already you have a datetime and you want to convert. see below:

datetime = "3/23/2018 11:43:51 AM"

We can split the date and time.

var date = new Date(datetime).toLocaleDateString();
var time = new Date(datetime).toLocaleTimeString();

var splitdatetime = date + " " + time;

This is Angular4. it work fine for all browsers.

Omar Einea
  • 2,478
  • 7
  • 23
  • 35