如何将某些Date对象转换为德国的相应时间?

问题描述

假设我有一个类似这样的Date对象:

let datetoConvert = new Date(date_string) // represents certain time like 12th Aug 11PM in India

我要实现的是设计这样的功能

getGermanDate(datetoConvert): Date {
   // What should be written here?
}

函数应该返回datetoConvert对象中德国时间的Date对象。

谢谢。

解决方法

您可以使用本机JavaScript函数进行转换(toLocaleString),也可以使用moment timezone(更为灵活)。

对于toLocaleString调用,我还指定了德国日期格式(通过将“ de-DE”传递给locale参数,您可以使用所需的任何语言环境。

function getGermanDate(input) {
    return moment.tz(input,"Europe/Berlin");
}

/* Using moment timezone */
let timestamp = "2020-08-12 23:00:00";
let timeIndia = moment.tz(timestamp,"Asia/Kolkata");
let timeGermany = getGermanDate(timeIndia);
console.log("Time (India):",timeIndia.format("YYYY-MM-DD HH:mm"));
console.log("Time (Germany):",timeGermany .format("YYYY-MM-DD HH:mm"));

/* Using native JavaScript */
let dateToConvert = new Date("2020-08-12T23:00:00+0530");

console.log("Time (India,native):",dateToConvert.toLocaleString('en-IN',{ timeZone: 'Asia/Kolkata' }));
console.log("Time (Germany,dateToConvert.toLocaleString('de-DE',{ timeZone: 'Europe/Berlin' }));
<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>

,

许多其他问题都涵盖了javascript日期格式。可以使用带有toLocaleString timeZone 选项来指定特定的时区,或者使用Intl.DateTimeFormat constructor format 选项来进行更多控制(使用IANA representative location以应用历史更改和DST更改),例如

let d = new Date();

// toLocaleString,default format for language de
console.log(d.toLocaleString('de',{timeZone:'Europe/Berlin',timeZoneName: 'long'}));

// DateTimeFormat.format with specific options
let f = new Intl.DateTimeFormat('de',{
  year: 'numeric',month: 'short',day: 'numeric',hour: '2-digit',hour12: false,minute: '2-digit',timeZone: 'Europe/Berlin',timeZoneName: 'short'
});
console.log(f.format(d));

您可能还对this answer感兴趣。