Keywords: AngularJS | DateTime Formatting | Date Object | Custom Filter | Timezone Handling
Abstract: This article provides an in-depth analysis of proper datetime formatting in AngularJS. By examining common error scenarios, it focuses on the core solution of converting strings to Date objects and presents multiple implementation approaches including built-in filters, custom filters, and third-party library integration. The article also delves into date format string syntax and timezone handling mechanisms to help developers avoid common formatting pitfalls.
Problem Background and Common Errors
In AngularJS development, datetime formatting is a common but error-prone task. Many developers encounter issues where the date filter fails to work properly, primarily because the input data is not a valid Date object.
A typical error scenario is shown below:
Input data: {{v.Dt}}
Applied filter: {{v.Dt | date:'yyyy-MM-dd HH:mm:ss Z'}}
Actual output: 2012-10-16T17:57:28.556094Z
Expected output: 2010-10-28 23:40:23 0400 or 2010-10-28 23:40:23 EST
Core Solution: Ensure Input is a Date Object
AngularJS's date filter requires the input to be a JavaScript Date object. If the input is an ISO format string (like 2012-10-16T17:57:28.556094Z), it must be converted first.
Correct implementation in the controller:
// Convert string to Date object
scope.v.Dt = Date.parse(scope.v.Dt);
After conversion, the filter works correctly:
{{v.Dt | date:'yyyy-MM-dd HH:mm:ss Z'}}
Date Format String Details
AngularJS date format strings follow specific rules:
yyyy: Four-digit yearMM: Two-digit month (01-12)dd: Two-digit day (01-31)HH: 24-hour format hour (00-23)mm: Minutes (00-59)ss: Seconds (00-59)Z: Timezone offset (e.g., +0800)
Dynamic Format Configuration
Formats can be specified dynamically through scope variables:
// Define format in controller
scope.dateFormat = 'yyyy-MM-dd HH:mm:ss Z';
// Use in template
{{dt | date:dateFormat}}
Custom Filter Solution
For scenarios requiring multiple date format handling, create a custom filter:
app.filter("asDate", function () {
return function (input) {
return new Date(input);
}
});
Usage pattern:
{{item.myDateTimeString | asDate | date:'shortDate'}}
Enhancing Functionality with Moment.js
For complex date operations, integrate Moment.js:
angular.module('myModule').filter('moment', function () {
return function (input, momentFn /*, param1, param2, ...param n */) {
var args = Array.prototype.slice.call(arguments, 2),
momentObj = moment(input);
return momentObj[momentFn].apply(momentObj, args);
};
});
Application examples:
{{ anyDateObjectOrString | moment: 'format': 'MMM DD, YYYY' }}
{{ anyDateObjectOrString | moment: 'fromNow' }}
Using Date Filter in Controllers
Beyond template usage, the filter can be invoked in JavaScript code:
var today = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss Z');
Timezone Handling Considerations
Important considerations for cross-timezone applications:
- The
Zformat specifier displays local timezone offset - UTC times require specialized UTC handling methods
- Server times are typically stored in UTC and need conversion to local time for display
Best Practices Summary
1. Always ensure input data is a valid Date object
2. For string inputs, use Date.parse() or new Date() for conversion
3. Use custom filters for complex date conversion logic
4. Consider using specialized libraries like Moment.js for complex date operations
5. Flexibly apply date formatting functionality in both controllers and templates