我听说new Date()应该返回系统时区的日期,但由于某种原因,我得到的是UTC时区而不是2021-05-28T04:00:00.000Z。为什么会发生这种情况,我如何才能得到本地时区的当前时间(使用Expo处理React Native项目)?
new Date()
2021-05-28T04:00:00.000Z
r6vfmomb1#
试试这个:
new Date().toLocaleString()
仅限日期:
new Date().toLocaleDateString()
仅限时间:
new Date().toLocaleTimeString()
imzjd6km2#
我是这样处理的:
const d = new Date();const month = d.getMonth() + 1; // it returns 0 for January and 11 for December const day = d.getDate();const year = d.getFullYear();const hours = d.getHours() + 1; // for UTC+1 , const minutes = "0" + d.getMinutes();const seconds = "0" + d.getSeconds();const formattedTime = day + '.' + month + '.' + year + ', ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);console.log(formattedTIme); // Output: 2.12.2021, 16:47:47
const d = new Date();
const month = d.getMonth() + 1; // it returns 0 for January and 11 for December
const day = d.getDate();
const year = d.getFullYear();
const hours = d.getHours() + 1; // for UTC+1 ,
const minutes = "0" + d.getMinutes();
const seconds = "0" + d.getSeconds();
const formattedTime = day + '.' + month + '.' + year + ', ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTIme);
// Output: 2.12.2021, 16:47:47
owfi6suc3#
我在代码中遇到了同样的问题,例如:
const c = {d1 : new Date(1672720648000)}console.log(c.d1.toString()) //Mon Jan 02 2023 20:37:28 GMT-0800 (Pacific Standard Time)console.log(JSON.stringify(c))//{"dd":"2023-01-03T04:37:28.000Z"}`c.d1 = c.d1.toString() // -> You can fix this issue by storing string in your jsonconsole.log(JSON.stringify(c))//{"d1":"Mon Jan 02 2023 20:37:28 GMT-0800 (Pacific Standard Time)"}
const c = {d1 : new Date(1672720648000)}
console.log(c.d1.toString()) //Mon Jan 02 2023 20:37:28 GMT-0800 (Pacific Standard Time)
console.log(JSON.stringify(c))//{"dd":"2023-01-03T04:37:28.000Z"}`
c.d1 = c.d1.toString() // -> You can fix this issue by storing string in your json
console.log(JSON.stringify(c))//{"d1":"Mon Jan 02 2023 20:37:28 GMT-0800 (Pacific Standard Time)"}
所以我意识到问题出在 JSON.stringify 的工作方式上。问题为非,* 日期 * 或 * React *。
3条答案
按热度按时间r6vfmomb1#
试试这个:
仅限日期:
仅限时间:
imzjd6km2#
我是这样处理的:
owfi6suc3#
我在代码中遇到了同样的问题,例如:
所以我意识到问题出在 JSON.stringify 的工作方式上。
问题为非,* 日期 * 或 * React *。