【问题标题】:Convert the date "Tue Aug 18 2020 12:30:44 GMT+0530" to "Tue Aug 18 2020 12:30:44 GMT+05:30"将日期“2020 年 8 月 18 日星期二 12:30:44 GMT+0530”转换为“2020 年 8 月 18 日星期二 12:30:44 GMT+05:30”
【发布时间】:2020-12-07 07:59:12
【问题描述】:

我正在使用new Date() 获取当前日期和时间,并将其添加为 div 标签的文本内容。

工作 sn-p:

const currentDateTime = new Date();
document.getElementById('demo').textContent = currentDateTime;
<div id="demo">
</div>

它工作正常,但我需要更改日期的格式。

发件人:

Tue Aug 18 2020 12:30:44 GMT+0530 (India Standard Time)

收件人:

Tue Aug 18 2020 12:30:44 GMT+05:30 (India Standard Time)

gmt like 需要添加冒号(:)

GMT+05:30

在实际应用程序中,我使用时刻 js 并使用 moment() 获取当前日期和时间。所以moment js的解决方式也会对我有所帮助。

【问题讨论】:

  • 尝试使用moment timezone并根据需要进行修改。
  • new Date().toString().replace(/(\d\d)( \(.*$)/, ':$1$2'); 没有图书馆,没有时区问题。

标签: javascript html date datetime momentjs


【解决方案1】:

我们可以使用“Z”格式标记来指示使用 moment.js 的 +-HH:mm 格式的 UTC 偏移量。我们还可以将格式字符串中的 GMT 文字包含为 [GMT]。记录在案here

我在这里使用 moment.tz 将时区强制为 +5:30,但假设它是您的当地时间,您只需使用 moment() 代替!

例如:

let m = moment.tz("Asia/Kolkata");
console.log(m.format("ddd MMM DD YYYY HH:mm:ss [GMT]Z"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data-10-year-range.js"></script>

【讨论】:

    【解决方案2】:

    由于:的索引在您的情况下始终相同,您可以使用以下方法:

    const text = 'Tue Aug 18 2020 12:30:44 GMT+0530 (India Standard Time)'
    let textArr = text.split('')
    textArr.splice(31, 0, ":")
    const newText = textArr.join('')

    【讨论】:

    • 或text.replace(/([+\-])(\d\d)(\d\d)/, '$1$2:$3')。 :-)
    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 2016-10-05
    • 2020-12-26
    • 2016-12-16
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多