如何将日期从UTC转换为本地时区,并使用Restangular转换

时间:2014-04-14 12:36:48

标签: angularjs restangular

我在我的Node / express服务器上以UTC格式存储日期,并使用Restangular在客户端上获取和发布数据。是否可以使用restangular addResponseInterceptor和addRequestInterceptor方法将Date从UTC转换为本地时间,将本地时间转换为UTC。

2 个答案:

答案 0 :(得分:2)

这篇文章是我的解决方案。工作得很好 - 只有我做的更改是添加一个toLocal标志,我在Response拦截器上设置为true,而在Request上设置为false,然后用它来做适当的切换..

http://aboutcode.net/2013/07/27/json-date-parsing-angularjs.html

function convertDateStringsToDates(input, toLocal) {
  // Ignore things that aren't objects.
  if (typeof input !== "object") return input;

for (var key in input) {
    if (!input.hasOwnProperty(key)) continue;

    var value = input[key];
    var match;
    // Check for string properties which look like dates.
    if (typeof value === "string" && (match = value.match(regexIso8601))) {
        var milliseconds = Date.parse(match[0]);
        if (!isNaN(milliseconds)) {
            if (toLocal) {
                input[key] = moment.utc(new Date(milliseconds)).local().toDate();
            } else {
                input[key] = moment(new Date(milliseconds)).utc().toDate();
            }

        }
    } else if (typeof value === "object") {
        // Recurse into object
        convertDateStringsToDates(value, toLocal);
    }
}
return input;

}

...然后

  .config([
    '$httpProvider', function($httpProvider) {

        $httpProvider.interceptors.push(function () {
            return {
                request: function(request) {
                    return convertDateStringsToDates(request,false);
                },

                response: function (response) {
                   // otherwise, default behaviour
                    return convertDateStringsToDates(response, true);
                }
            };
        });
    }
])

答案 1 :(得分:0)

你可以在restangular变换器中将String转换为Date(用于GET),类似这样

RestangularConfigurer
  .addElementTransformer('<RESTRESOURCENAME>', false, function (element) {
      element.createDate = new Date(element.createDate);
      return element;
  })