从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。

如何使用JavaScript或jQuery来做到这一点?


当前回答

我相信这是最好的解决方案:

  let date = new Date(objDate);
  date.setMinutes(date.getTimezoneOffset());

这将根据偏移量适当地更新您的日期,因为它是以分钟为单位的。

其他回答

如果有人想要显示转换后的时间到特定id元素的函数,并应用日期格式字符串yyyy-mm-dd 这里date1是字符串,ids是time要显示的元素id。

function convertUTCDateToLocalDate(date1, ids) 
{
  var newDate = new Date();
  var ary = date1.split(" ");
  var ary2 = ary[0].split("-");
  var ary1 = ary[1].split(":");
  var month_short = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
  newDate.setUTCHours(parseInt(ary1[0]));
  newDate.setUTCMinutes(ary1[1]);
  newDate.setUTCSeconds(ary1[2]);
  newDate.setUTCFullYear(ary2[0]);
  newDate.setUTCMonth(ary2[1]);
  newDate.setUTCDate(ary2[2]);
  ids = document.getElementById(ids);
  ids.innerHTML = " " + newDate.getDate() + "-" + month_short[newDate.getMonth() - 1] + "-" + newDate.getFullYear() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
            }

我知道这个答案已经被接受了,但我来到这里是因为谷歌,我确实从接受的答案中得到了灵感,所以如果有人需要,我确实想分享它。

把这个函数记在脑子里:

<script type="text/javascript">
function localize(t)
{
  var d=new Date(t+" UTC");
  document.write(d.toString());
}
</script>

然后为页面主体中的每个日期生成以下内容:

<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>

删除GMT和时区,修改以下行:

document.write(d.toString().replace(/GMT.*/g,""));

使用dayjs库:

(new Date()).toISOString();  // returns 2021-03-26T09:58:57.156Z  (GMT time)

dayjs().format('YYYY-MM-DD HH:mm:ss,SSS');  // returns 2021-03-26 10:58:57,156  (local time)

(在nodejs中,你必须在使用它之前:const dayjs = require('dayjs'); 在其他环境下,请阅读dayjs文档。)

我有一个类似的问题,我使用以下代码代码(JavaScript)转换UTC到本地时间

let a = new Date() .toString a = a.getFullYear () () + "-" + ( a.getMonth () + 1) .toString()。padStart(2, "0") + "-" + a.getDate(). tostring()。padStart(“0”) console.log (a)

在我的例子中,我必须在几秒钟内找出日期的差异。日期是UTC日期字符串,因此我将其转换为本地日期对象。这就是我所做的:

let utc1 = new Date();
let utc2 = null;
const dateForCompare = new Date(valueFromServer);
dateForCompare.setTime(dateForCompare.getTime() - dateForCompare.getTimezoneOffset() * 
 60000);
utc2 = dateForCompare;

const seconds = Math.floor(utc1 - utc2) / 1000;