๋ฐ˜์‘ํ˜•

Date.toISOString() ๋ฉ”์„œ๋“œ๋Š” Date ๊ฐ์ฒด๋ฅผ ISO 8601 ํ˜•์‹์˜ UTC ์‹œ๊ฐ„์œผ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค. ์ฆ‰, ์–ด๋–ค ๊ฐ’์ด ๋“ค์–ด์˜ค๋“  ํ•ญ์ƒ UTC+0 ์‹œ๊ฐ„์œผ๋กœ ๋ณ€ํ™˜ํ•œ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค๋Š” ์˜๋ฏธ๋‹ค.

 

ํ•œ๊ตญ์€ UTC ๊ธฐ์ค€์‹œ๋ณด๋‹ค 9์‹œ๊ฐ„(540๋ถ„) ๋น ๋ฅด๊ธฐ ๋•Œ๋ฌธ์—(+9์‹œ๊ฐ„) toISOString() ๋ฉ”์„œ๋“œ๊ฐ€ ๋ฐ˜ํ™˜ํ•˜๋Š” ์‹œ๊ฐ„๊ณผ "ํ‘œ๋ฉด์ ์ธ" ์ฐจ์ด๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ์˜ˆ๋ฅผ๋“ค์–ด ํ˜„์žฌ ํ•œ๊ตญ ์‹œ๊ฐ„์ด 2022๋…„ 7์›” 8์ผ 01์‹œ 56๋ถ„์ด๋ผ๋ฉด toISOString ๋ฉ”์„œ๋“œ๋Š” ์ด๋ณด๋‹ค 9์‹œ๊ฐ„ ๋Šฆ์€ 2022-07-07T16:56... ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

// +09:00์€ UTC ๊ธฐ์ค€์‹œ ๋ณด๋‹ค 9์‹œ๊ฐ„ ๋น ๋ฅด๋‹ค๋Š” ๊ฒƒ์„ ๋ช…์‹œํ•œ ๊ฒƒ
const localDate = new Date('2022-07-08T01:56:00+09:00');

// ์ถœ๋ ฅ๊ฐ’: 2022-07-07T16:56:00.000Z
// Z๋Š” Zulu ์‹œ๊ฐ„๋Œ€์˜ ์•ฝ์–ด๋กœ UTC+0๊ณผ ๋™์ผ
console.log(localDate.toISOString());

 

๋งŒ์•ฝ ๋กœ์ปฌ ์‹œ๊ฐ„๋Œ€๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ISO 8601 ํฌ๋งท์˜ ๋ฌธ์ž์—ด์„ ์–ป๊ณ  ์‹ถ๋‹ค๋ฉด ๋ณ„๋„์˜ ์œ ํ‹ธ๋ฆฌํ‹ฐ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ์•„๋ž˜ ํ•จ์ˆ˜๋Š” ๋กœ์ปฌ ์‹œ๊ฐ„๋Œ€ ์˜คํ”„์…‹์„ ๊ณ„์‚ฐํ•˜์—ฌ ํ•ด๋‹น ์‹œ๊ฐ„๋Œ€๋ฅผ ๊ธฐ์ค€์œผ๋กœ ํ•œ ISO ๋ฌธ์ž์—ด์„ ์ƒ์„ฑํ•œ๋‹ค. ๋ฐ˜ํ™˜ํ•œ ๋ฌธ์ž์—ด์—” ์˜คํ”„์…‹ ์ •๋ณด๋ฅผ ๊ทธ๋Œ€๋กœ ํฌํ•จํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ํ•„์š”์— ๋”ฐ๋ผ UTC ๋˜๋Š” ๋‹ค๋ฅธ ์‹œ๊ฐ„๋Œ€๋กœ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.

const toLocaleISOString = (utcDate) => {
  // ๋กœ์ปฌ ์‹œ๊ฐ„๋Œ€์™€ UTC ์‹œ๊ฐ„๋Œ€์˜ ์ฐจ์ด๋ฅผ ๋ถ„ ๋‹จ์œ„๋กœ ๋ฐ˜ํ™˜
  // e.g. -540 (utcDate๋Š” ๋กœ์ปฌ ์‹œ๊ฐ„๋Œ€๋ณด๋‹ค 540๋ถ„ ๋Š๋ฆผ)
  const offset = utcDate.getTimezoneOffset();

  // offset์ด ์–‘์ˆ˜๋ฉด ์‹œ๊ฐ„๋Œ€ ๊ธฐํ˜ธ๋ฅผ '-'๋กœ, ์Œ์ˆ˜๋ฉด '+'๋กœ ์„ค์ •
  const offsetSign = offset > 0 ? '-' : '+';

  // ์ˆซ์ž๋ฅผ ๋‘ ์ž๋ฆฌ ๋ฌธ์ž์—ด๋กœ ํฌ๋งคํŒ…ํ•˜๋Š” ํ•จ์ˆ˜ e.g. 2 => '02'
  const pad = (num) => String(num).padStart(2, '0');

  // ์˜คํ”„์…‹์„ ์‹œ๊ฐ„ ๋‹จ์œ„๋กœ ๋ณ€ํ™˜ e.g. 540 / 60 = 9 => '09'
  const offsetHours = pad(Math.floor(Math.abs(offset) / 60));

  // ์˜คํ”„์…‹์˜ ๋‚จ์€ ๋ถ„ ๊ณ„์‚ฐ e.g. 540 % 60 -> '00'
  const offsetMinutes = pad(Math.abs(offset) % 60);

  // getTime() ๋ฉ”์„œ๋“œ๋Š” 1970๋…„ 1์›” 1์ผ 00:00:00 UTC ์ดํ›„ ๊ฒฝ๊ณผ๋œ ์‹œ๊ฐ„์„ ๋ฐ€๋ฆฌ์ดˆ ๋‹จ์œ„๋กœ ๋ฐ˜ํ™˜
  // ๋”ฐ๋ผ์„œ offset ๊ฐ’์—๋„ 60 * 1000์„ ๊ณฑํ•ด์„œ ๋ฐ€๋ฆฌ์ดˆ ๋‹จ์œ„๋กœ ๋งŒ๋“ค์–ด์„œ ๊ณ„์‚ฐ
  const localISOString = new Date(utcDate.getTime() - offset * 1000 * 60)
    .toISOString() // e.g. '2022-07-08T01:56:00.000Z'
    .slice(0, -1); // ISO ๋ฌธ์ž์—ด์—์„œ 'Z' ์ œ๊ฑฐ (Z๋Š” Zulu ์‹œ๊ฐ„๋Œ€์˜ ์•ฝ์ž๋กœ UTC+0๊ณผ ๋™์ผ)

  return `${localISOString}${offsetSign}${offsetHours}:${offsetMinutes}`;
};

// ๋กœ์ปฌ ์‹œ๊ฐ„๋Œ€ ๊ธฐ๋ฐ˜ ISO ๋ฌธ์ž์—ด ์ถœ๋ ฅ => '2022-07-08T01:56:00.000+09:00'
toLocaleISOString(new Date('2022-07-07T16:56:00.000Z'));
๋ฐ˜์‘ํ˜•