Let's say I have a Date object like this:
let dateToConvert = new Date(date_string) // represents certain time like 12th Aug 11PM in India
What I want to achieve is to design a function like this:
getGermanDate(dateToConvert): Date {
// What should be written here?
}
The function should return Date object that is the time in Germany at the time that is in dateToConvert object.
Thanks in advance.
You could use native JavaScript functions to convert (toLocaleString), or you could use moment timezone (which is more flexible).
For the toLocaleString call I'm also specifying a Germany date format (by passing "de-DE" to the locale parameter, you could use whichever locale you wish.
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, native):", 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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments