Abaij
Abaij

Reputation: 873

What is an easy way to format datetime in angularjs?

I've been around for hours to find out how to format datetime in angularjs, but there's no easy way, too complicated. I wonder if there is.

So, I have a datetime string like 2019-06-14 12:15:00. I want to format it to 14 Jun 2019 12:15:00. I tried this in the view:

{{ '2019-06-14 12:15:00' | date : 'dd MMM yyyy hh:mm:ss' }}

No, it's not working. I wonder if there's a simple way to do it. May be there's a built-in function in angular or javascript?

Upvotes: 2

Views: 60

Answers (2)

NTP
NTP

Reputation: 4448

As others have mentioned your string is not a valid date string format but it is very close one. So an easy solution for you can be instead of creating a new date object you can find a way to convert your string to a valid date string. You can try the following:

{{ data.replace(" ", "T") | date : 'dd MMM yyyy hh:mm:ss' }}

where data is your date string.

Demo

Upvotes: 0

Artisan
Artisan

Reputation: 2124

When trying to get date manipulation right - it can get hairy and difficult, I feel your pain.

I would go the route and create my own angular filter, I've found for serious date work especially with timezones, the built in angular date filter doesn't quite scratch that itch. I've also found heaps of benefit in using moment.js and moment.js timezones

https://momentjs.com/

The beauty of moment is that it does a lot of the heavy lifting when it comes to date parsing and very flexible. Here is an example of a filter that fit my needs and may fit yours:

angular.module("global-app")
.filter('datetz', function ($filter) {
    return function (date, dateFormat, timeZone) {
        let new_date = date;
        if (new_date == null) return null;
        // Default timezone to Sydney if none selected
        if (timeZone == null) timeZone = "Australia/Sydney";
        if (new_date && timeZone) {
            new_date = moment.tz(new_date, timeZone);
            timeZone = new_date.format('Z');
            new_date = new_date.toDate();
        }
        return $filter('date')(new_date, dateFormat, timeZone);
    }
});

To use it:

{{ "2019-06-12 05:00" | datetz: "dd MMM yyyy hh:mm:ss": "America/Detroit" }}

The benefit of using the TZ database name for the timezone rather than the "+10:00" format that the default angular filter expects is that you have to know that it is +10 and not +11 for the date your putting through the filter, whereas using the TZ database name will let the timezone offset calculation happen automatically based on the date your filtering using the TZ database that moment provides.

I know you didn't ask for it but thought it would still be of benefit for you and others that might stumble upon this.

Happy coding

Upvotes: 1

Related Questions