Angular JS - 提交到 $http 时日期更改 - 时区问题 [英] Angular JS - Date changes when submitting to $http - Timezone issue

查看:21
本文介绍了Angular JS - 提交到 $http 时日期更改 - 时区问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,当 Date 通过 $http.put 传递给 API 时发生变化,我怀疑是时区问题:

I am having a strange problem where a Date changes when it is passed to API through $http.put, I suspect a timezone issue:

Datepicker 触发 ng-change 事件 - console.log:

Datepicker triggers ng-change event - console.log:

2014 年 6 月 10 日星期二 00:00:00 GMT+0100(GMT 夏令时)

使用 Angular 传递给 API $http.put...

Passed to API using Angular $http.put...

当它击中 Fiddler 时:

When it hits Fiddler:

StartDate=2014-06-09T23:00:00.000Z

如您所见,日期从 6 月 10 日更改为 6 月 9 日.

As you can see the date changes from 10th June to 9th June.

我怎样才能停止这种日期更改?是时区导致更改吗?API 和客户端都在本地主机上运行.

How can I stop this change of date? Is it the timezone causing the change? Both the API and client side are running on Localhost.

更进一步:

当该字段被第二次点击并且日期选择器启动/选择日期时,第二次没有出现问题:

When the field is clicked a second time and the datepicker launched / date selected, this second time the problem does not appear:

控制台.log:

2014 年 8 月 6 日星期三 22:00:00 GMT+0100(GMT 夏令时间)

收到的提琴手数据:

StartDate=2014-08-06T21:00:00.000Z

推荐答案

我认为这是一个 TZ 问题,b/c 你的 GMT+0100 和你的 StartDate=2014 之间的差异-06-09T23:00:00.000Z5 小时.

I think it is a TZ issue, b/c the difference between your GMT+0100 and your StartDate=2014-06-09T23:00:00.000Z is 5 hours.

.

您的当地时间目前是 BST(英国夏令时间),相当于 GMT +1

Your local time is currently BST (British Summer Time) equivalent to GMT +1

这将是您进行 API 调用时的默认时间.

This is going to be the default time when you make your API call.

但是,该 API 是由 Google 在加利福尼亚州编写的,它们相当以自我为中心.因此,它们会自动转换时间,因为您没有提供任何 date 格式说明".

However, the API was written by Google in California, and they are rather egocentric. Therefore, they're automatically converting the time since you're not providing any date formatting "instructions".

换句话说,当您打印到 console.log() 时,Chrome 会很好地为您完成转换,但是当您制作 $http.put 时,Angular,无需为您提供显式格式,使用其默认 TZ(即 PST)进行调用

In other words, Chrome does the conversion for you nicely when you print to the console.log(), but when you make your $http.put, Angular, without explicit formatting for you, makes the call using it's default TZ (which is PST)

.

您需要将日期格式强制设置为您的语言环境.

You need to force the date formatting to your locale.

  • 角度模板

  • Angular template

{{ date_expression | date : 'yyyy-MM-dd HH:mm:ss'}}

  • 在 JavaScript 中

  • In JavaScript

    $filter('date')(date, 'yyyy-MM-dd HH:mm:ss')
    

  • 使用本地化

  • using localization

    <html>
      <head>
        <title>My Angular page</title>
        <script src="angular-locale_en-uk.js"></script>
        ...
      </head>
      <body>
        ...
      </body>
    </html>
    

  • 这篇关于Angular JS - 提交到 $http 时日期更改 - 时区问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆