将服务器时区转换为本地时间

Converting server timezone to localtime momentjs

本文关键字:时间 转换 服务器 时区      更新时间:2023-09-26

我的服务器是在EDT -4,我试图在我的数据库转换日期到用户的本地时区使用momentj。我什么都试过了,但都不行。

这些是我尝试过的事情:

//1
var servertime= array[data].time
var localtime= moment(servertime).toDate();
var time = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
//Actual Database time: 2015-10-20 12:42:47    Output:2015-10-20 12:42:47
//2
var servertime= array[data].time
var localtime= moment.utc(servertime).toDate();
var time = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
//Actual Database time: 2015-10-20 12:42:47    Output:2015-10-20 12:42:47

似乎瞬间并没有改变它。

例如服务器上的UTC时间为:October 20, 2015 17:29我的电脑时钟UTC +1是2015年10月20日7:30

你几乎每件事都做对了。你的主要问题是你在localtime变量中存储javascript日期对象。

//I'm assuming your this is your server time. This assumes your server time is in UTC.
var servertime= '2015-10-20 12:42:47';
//Create a utc moment, then convert it to the local time. localtime is a momentjs object.
var localtime = moment.utc(servertime).local();
//format the local time
var time = localtime.format('YYYY-MM-DD HH:mm:ss');

.utc().local()分别转换UTC和本地时间显示的时间。详细信息请参见http://momentjs.com/docs/#/parsing/utc/

显然,在我的数据库中插入的时间不是unix时间,所以我改变了我的php代码,而不是mysql使用php时间()函数的current_timestamp。然后我在php中使用日期('c',mytimedata)使其以适当的格式使用。然后简单地使用:

 var localTime  = moment(array[data].time).toDate();