dspld86684 2015-02-18 23:18
浏览 50
已采纳

Javascript - 显示来自mySQL TimeDate的区域设置时间

I am having an issue with displaying the correct time. I have a php script that when a button is clicked it inserts the CURRENT_TIMESTAMP into the database. The server is located in Arizona, I am in PST. When I call the time in my script it shows Arizona time, but I need it to show the users time. So 2015-02-18 16:06:28 Arizona time, MY time is 2015-02-18 15:06:28.

How do i get the correct time. I am using moment.js, but no matter how i format it it shows the incorrect time. I am not sure but is DST, not being considered?

var time_in = time_in;//format 2015-02-18 16:17:33
var timeIn = moment.utc(time_in, "HH:mm a").format("HH:mm a");
  • 写回答

2条回答 默认 最新

  • 普通网友 2015-02-19 00:15
    关注

    Moment.js parses the date as a locale date-time. So when you do moment.utc(time_in), you're converting it to UTC according to your local time (PST), shifted forward or backwards.

    So what you need to do is do a moment.fn.utcOffset. Arizona is UTC-07:00, so we would want to add +7 to the offset. You can do the same using moment.fn.zone but that's getting deprecated.

    var utcTime = moment.utc('2015-02-18 16:06:28').utcOffset(+7).format('YYYY-MM-DD HH:mm:ss')
    // returns "2015-02-18 23:06:28" which is the UTC time
    

    Now you have the moment in UTC, you can convert it to the client localtime:

    moment(moment.utc(utcTime).toDate()).format('YYYY-MM-DD HH:mm:ss')
    // returns '2015-02-18 15:06:28' (which is PST)
    

    moment.utc(utcTime).toDate() above just converts the utc time to your local time, then formatting it with momentjs

    EDIT: If possible, you should use unix timestamp when sending to server, then you don't have to deal with UTC or timezones. You can convert to local time with moment.unix(unixTimestamp).format('YYYY-MM-DD HH:mm:ss')

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器