You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用date-fns提取日期字符串中的本地时间及时区偏移信息

Hey there! Let's figure out how to do this with date-fns. First, a quick heads-up: JavaScript's built-in Date object doesn't store the original timezone offset from your ISO string—it only keeps a timestamp representing the exact moment in UTC. So completely avoiding any string handling to grab that exact +02:00 or 2 offset isn't possible, but we can use date-fns for the datetime extraction and keep string work to an absolute minimum.

1. Extract the datetime portion (2022-04-16T18:31)

If you want the exact datetime from your input string (not converted to your local timezone), you'll need date-fns-tz—the timezone extension for date-fns. Standard date-fns only formats dates in your local timezone or UTC by default, which won't give you the original 18:31 if you're in a different timezone.

First, install the packages if you haven't already:

npm install date-fns date-fns-tz

Then parse and format the date using the original timezone:

import { parseISO } from 'date-fns';
import { formatInTimeZone } from 'date-fns-tz';

const isoString = "2022-04-16T18:31:00+02:00";
const date = parseISO(isoString);

// Grab the timezone offset from the string (super minimal string handling)
const originalTimeZone = isoString.match(/([+-]\d{2}:\d{2})$/)[0];

// Format the date in the original timezone, down to minutes
const targetDateTime = formatInTimeZone(date, originalTimeZone, "yyyy-MM-dd'T'HH:mm");
console.log(targetDateTime); // Logs: "2022-04-16T18:31"

If you don't care about preserving the original timezone and just want your local timezone's version of that moment, you can use plain date-fns:

import { parseISO, format } from 'date-fns';

const date = parseISO(isoString);
const localDateTime = format(date, "yyyy-MM-dd'T'HH:mm");
// Note: This outputs the time in YOUR local timezone, not the original +02:00

2. Extract the timezone offset

Option 1: Get the offset as a number (2)

Using the originalTimeZone string we grabbed earlier, converting it to a number is straightforward:

// For positive offsets like +02:00
const offsetHours = parseInt(originalTimeZone.slice(1, 3), 10);
// For negative offsets (e.g., -05:00), include the sign: parseInt(originalTimeZone.slice(0, 3), 10)
console.log(offsetHours); // Logs: 2

Option 2: Get the formatted offset string (+02:00)

We already have this from the originalTimeZone variable above. If you wanted to calculate an offset from the date object (warning: this gives your local timezone offset, not the original one), you can use date-fns' getUTCOffset:

import { parseISO, getUTCOffset } from 'date-fns';

const date = parseISO(isoString);
const offsetMinutes = getUTCOffset(date);

// Format to ±HH:mm format
function formatOffset(minutes) {
  const sign = minutes >= 0 ? '+' : '-';
  const hours = Math.floor(Math.abs(minutes) / 60);
  const mins = Math.abs(minutes) % 60;
  return `${sign}${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`;
}

console.log(formatOffset(offsetMinutes)); // Logs your local timezone offset, not +02:00 unless you're in UTC+2

Key Takeaway

The Date object discards the original timezone offset once it parses the ISO string—so to get that exact offset from your input, you have to pull it directly from the string itself. Date-fns is perfect for handling the datetime formatting, but it can't retrieve an offset that's no longer stored in the parsed date.

内容的提问来源于stack exchange,提问作者Jacobdo

火山引擎 最新活动