首页 > 解决方案 > Reactjs 时区转换

问题描述

我已连接 mssql 数据库并获取一些信息,包括 Date_Time。

时间快到了2021-01-30T15:08:25.357Z。我想将其转换为dd-mm-yy hh:mm:ss格式。所以,应该是30-01-2021 15:08:25

我使用了这种方法,但这并不完全是我想要的。

 var d1 = new Date(datey).toLocaleDateString("tr")
  var newTime=d1+" "+
  new Date(datey).getUTCHours()+":"+
  new Date(datey).getUTCMinutes()+":"+
  new Date(datey).getUTCSeconds()
  // it returns 30/01/2021 15:8:25

也许,在那里,我想看到 0 的时间格式,例如 15:08。凌晨 2 点时只有 2:0,但我想在 02:00 看到它。

我该怎么办,有什么想法吗?

标签: node.jsreactjsdatetime

解决方案


我建议使用诸如moment.js之类的日期/时间库,这将使日期操作更加容易,解析和格式化您的日期非常简单:

const input= "2021-01-30T15:08:25.357Z";
console.log("Input date:", input);

// To convert the date to local before displaying, we can use moment().format()
const formattedDateLocal = moment(input).format("DD-MM-YY HH:mm:ss");
console.log("Formatted date (Local Time):", formattedDateLocal );

// To display the UTC date, we can use moment.utc().format()
const formattedDateUTC = moment.utc(input).format("DD-MM-YY HH:mm:ss");
console.log("Formatted date (UTC):", formattedDateUTC );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>


推荐阅读