Aral Roca
Aral Roca

Reputation: 5919

Angular-moment with ISO string

I'm using amCalendar filter from angular-moment to show the moment in the view.

The amCalendar filter not accept Date as a type. I created this function that returns the short date ISO string passing a Date parameter:

function toShortISO(d){
        var date;
        date instanceof Date?
            date = d:
            date = toDate(d);

        function pad(n) {return n<10 ? '0'+n : n}
        return date.getUTCFullYear()
            + pad( date.getUTCMonth() + 1 )
            + pad( date.getUTCDate() )
            + 'T' + pad( date.getUTCHours() )
            + pad( date.getUTCMinutes() )
            + pad( date.getUTCSeconds() )
            + 'Z';
    }

Passing a Date, this function returns 20150905T060000Z (per example). And now I can apply the amCalendar filter with this string.

In the view is showing "Today 2:30 AM" as expected, but there is this warning in the console:

Console warning

Reference: https://github.com/moment/moment/issues/1407

In the reference explain that is necessary to create a moment object to solve this, but I don't know how, I think the example is for nodeJS not for angularJS.

I try this:

function toShortISO(d){
        return moment(d.toISOString());
}

But don't work.

Any suggestion?

Thank you!

Upvotes: 0

Views: 3742

Answers (1)

road2victory
road2victory

Reputation: 496

To get rid of the warning, you need to either:

Pass in an ISO formatted version of your date string:

  moment('2014-04-23T09:54:51');

Pass in the string you have now, but tell Moment what format the string is in:

  moment('Wed, 23 Apr 2014 09:54:51 +0000', 'ddd, DD MMM YYYY HH:mm:ss ZZ');

Convert your string to a JavaScript Date object and then pass that into Moment:

  moment(new Date('Wed, 23 Apr 2014 09:54:51 +0000'));

The last option is a built-in fallback that Moment supports for now, with the deprecated console warning. They say they won't support this fallback in future releases. They explain that using new Date('my date') is too unpredictable.

Basically you need to tell moment how to parse your date format, like this:

 var parsedDate = moment.utc("150423160509", "YYMMDDHHmmss");
 var a = parsedDate.tz("Asia/Taipei");
 // I'm assuming you meant HH:mm:ss here
 console.log( a.format("YYYY-MM-DD HH:mm:ss") );

Upvotes: 3

Related Questions