AngularJS: How to format ISO8601 date format?

2019-01-25 06:09发布

问题:

I am using bootstrap-datetimepicker and using ISO8601 datetime format as yyyy-mm-ddThh:ii:ssZ as mentioned in their options section

In my controller, I do

transaction.date = $('.form_datetime input').val();

which sends the data to backend as (console.log)

created_on: "Wed, 08 May 2013 23:18:32 -0000"

and saves in database as

2013-05-08 16:18:32-07

In my template, I do

<td>{{ transaction.created_on | date:'medium'}}</td>

and I see the output on my HTML as

Wed, 08 May 2013 23:18:32 -0000

But as per the Angular doc, it should be for format Oct 28, 2010 8:40:23 PM

What is that I am missing?

回答1:

I don't understand why no one provided the simple answer of using the correct format in the filter?

{{item.date | date:'yyyy-MM-ddTHH:mm:ssZ'}}

That will format as ISO-8601



回答2:

For now, I have created a filter

angular.module('customFilters', []).
  filter('dateInMillis', function() {
    return function(dateString) {
      return Date.parse(dateString);
    };
  });

added as dependency in app.js as

var app = angular.module('myApp', [
  '$strap.directives', 'ngCookies', 'categoryServices', 'transactionServices',
  'customFilters'
]);

and in HTML used it as

<!-- added dateInMillis to pass to date to filter Angular way -->
<td>{{ transaction.created_on | dateInMillis | date: 'medium'}}</td>

and that presents date on HTML as

May 8, 2013 5:14:36 PM 

If you know a better idea, please let me know



回答3:

In Brazil (and most of Europe, Australia, etc.), we use the default MySQL DATETIME on DB's:

"Y-m-d HH:ii:ss"

But use date() to display it like this:

"d/m/Y HH:ii:ss"

So in order to display that date in angular, "correctly", create a filter:

var app = angular.module(...

// Converts MySQL datetime into readable BR format
/*
    Converts 2013-10-18 18:47:15 into 1382122035000 so angular can format date 
    using brazilian standards
*/
app.filter('brDateFilter', function() {
    return function(dateSTR) {
        var o = dateSTR.replace(/-/g, "/"); // Replaces hyphens with slashes
        return Date.parse(o + " -0000"); // No TZ subtraction on this sample
    }
});

Then, on your angular app, just call the filter and format the value for display:

{{ item.datetime_value | brDateFilter | date:"dd/MM/yyyy HH:mm" }}

That covers date format in Brazilian, UK, New Zealand, etc. date format for angular, just subtract the timezone correctly.



回答4:

Beside all this, just you have change like this,

<td>{{ transaction.created_on | date:'medium'}}</td>

try to wirte it as

<td>{{ transaction.created_on | date:'MMM d, y h:mm:ss a'}}</td>