JavaScript - 时刻与... Date.toLocaleDateString不断返回我的时间

时间:2018-06-04 08:37:55

标签: javascript momentjs

我开始使用Moment库尝试使用以下代码为德国留出时间:

import moment from 'moment'
import 'moment/locale/de'

moment.locale('de');
console.log(moment().format('LTS'));

然而,它一直在回归我的英国夏令时间(BST)

我想也许这是图书馆的一个问题,所以我重新编写它而不使用这样的库:

const options = { hour: 'numeric', minute: 'numeric', second: 'numeric' }
const test = new Date();
console.log(test.toLocaleDateString('de-DE', options));

然而,这也会回归我的时间......(按照预期添加日期,月份和年份)

我做错了吗?或者这可能与Chrome输出到控制台的方式有关?

3 个答案:

答案 0 :(得分:1)

时刻区域设置是指语言而不是时区。

您需要moment timezone

moment().tz('CET').format('LTS')

修改

正如RobG所建议的那样,也可以毫不费力地实现:

new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' });



document.getElementById('date').innerHTML = new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' });

<div id="date"/>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下是使用moment -

执行此操作的方法

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}

console.log(toTimeZone(new Date(), "UTC"));
<script src="http://momentjs.com/downloads/moment.min.js"></script>

答案 2 :(得分:0)

使用 toLocaleString ,您可以使用 timeZone 选项,但在您需要的任何地方都可能不支持它:

var options = {hour: 'numeric', minute: 'numeric', second: 'numeric', timeZone: 'Europe/Berlin'};
var test = new Date();
console.log(test.toLocaleDateString('de-DE', options));