0

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.

Parth Savaliya
  • 353
  • 6
  • 13

2 Answers2

3

Formatting of javascript dates is covered in numerous other questions. A particular timezone can be specified using the timeZone option with toLocaleString or for more control use the Intl.DateTimeFormat constructor and format option (timezones are specified using an IANA representative location to apply historic and DST changes), e.g.

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));

You might also be interested in this answer.

RobG
  • 142,382
  • 31
  • 172
  • 209
2

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>
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40