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 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)