简体   繁体   English

如何获取时区为 int 的日期?

[英]How to get Date with timezone as int?

how can I get date in this format in JS?如何在 JS 中获取这种格式的日期? I tried using .toISOString() but I don't quite get the result that I need.我尝试使用.toISOString()但我没有得到我需要的结果。

2022-12-22 11:35:23 -0400

Thanks谢谢

I don't know any fast way, but you can use something like this: To get a date in the format "YYYY-MM-DD HH:mm:ss ZZ" in JavaScript, you can use the following code:我不知道有什么快速的方法,但你可以使用这样的方法:要在 JavaScript 中获取格式为“YYYY-MM-DD HH:mm:ss ZZ”的日期,你可以使用以下代码:

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1; // months are zero-indexed, so we need to add 1
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const timeZoneOffset = date.getTimezoneOffset();
const timeZoneOffsetHours = Math.floor(Math.abs(timeZoneOffset) / 60);
const timeZoneOffsetMinutes = Math.abs(timeZoneOffset) % 60;
const timeZoneOffsetString = (timeZoneOffset < 0 ? '+' : '-') +
    (timeZoneOffsetHours < 10 ? '0' : '') + timeZoneOffsetHours +
    ':' + (timeZoneOffsetMinutes < 10 ? '0' : '') + timeZoneOffsetMinutes;

const formattedDate = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day} ${hours}:${minutes}:${seconds} ${timeZoneOffsetString}`;

This will give you a string like "2022-12-22 11:35:23 -0400".这将为您提供类似“2022-12-22 11:35:23 -0400”的字符串。

This is tricky to do with vanilla JavaScript, however it's simple to do using a library such as luxon .使用 vanilla JavaScript 很难做到这一点,但是使用诸如luxon类的库很容易做到。

We create a new DateTime object, date , then call DateTime.toFormat() to present the date in the desired format.我们创建一个新的 DateTime object, date ,然后调用DateTime.toFormat()以所需格式显示日期。

 const { DateTime } = luxon; const date = DateTime.now(); console.log('Formatted date:', date.toFormat('yyyy-MM-dd HH:mm:ss ZZZ'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" integrity="sha512-6ZJuab/UnRq1muTChgrVxJhSgygmL2GMLVmSJN7pcBEqJ1dWPbqN9CiZ6U3HrcApTIJsLnMgXYBYgtVkJ8fWiw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

What format do you want?你要什么格式? Did you use Date ?你用过日期吗? Here is very useful library I use a lot.这是我经常使用的非常有用的库。 Date FNS there is format function and you can set format you want.日期 FNS有格式 function,您可以设置您想要的格式。 Function returns string Function 返回字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM