Use Cases (अपडेट: 2/6/2026)

Claude Code के साथ date और time handling गाइड

Claude Code से timezone, DST, Intl, test और DB date storage सुरक्षित बनाने की व्यावहारिक गाइड।

Claude Code के साथ date और time handling गाइड

Date-time logic को सिर्फ prompt पर छोड़ना क्यों खतरनाक है

Date और time के bug review में आसानी से छूट जाते हैं, लेकिन production में booking, billing, notification और SLA को बिगाड़ सकते हैं। भारत में स्क्रीन ठीक दिख सकती है, पर US daylight saving time, Europe month-end closing, India के 30-minute offset या server और browser timezone के फर्क पर टूट सकती है। अगर आप Claude Code से सिर्फ “date handling implement करो” कहेंगे, तो formatting ठीक मिल सकती है, लेकिन storage policy, API contract और boundary tests अधूरे रह सकते हैं।

Claude Code को code generator से ज्यादा date/time specification के pair engineer की तरह इस्तेमाल करें। यह guide reservation, subscription billing, notification, support SLA और admin dashboard जैसे cross-timezone web app के लिए है। पूरे testing workflow के लिए Claude Code testing strategies पढ़ें। Schema change के लिए database migration with Claude Code उपयोगी है।

Implementation से पहले official docs देखें। Display behavior के लिए MDN Intl.DateTimeFormat, Temporal की स्थिति और concepts के लिए TC39 Temporal proposal और MDN Temporal, PostgreSQL behavior के लिए PostgreSQL Date/Time Types, और Claude Code edits के बाद deterministic checks के लिए Claude Code hooks को आधार बनाएं।

पहले vocabulary और storage policy तय करें

Claude Code से code लिखवाने से पहले team की भाषा तय करें। वरना review में “हम UTC save करते हैं, इसलिए safe है” या “product local है, इसलिए एक timezone काफी है” जैसी कमजोर बातें रह जाती हैं।

शब्दआसान अर्थPractical rule
instantदुनिया में एक ही exact moment, जैसे 2026-06-02T00:00:00ZUTC-based timestamp के रूप में save करें
local dateuser या business calendar की date, जैसे birthday या due dateYYYY-MM-DD रखें, time से अलग
wall clock timeघड़ी में दिखने वाला time, जैसे 09:00 meetingIANA timezone ID के साथ save करें
IANA timezoneAsia/Kolkata या America/New_York जैसा region namefixed offset से replace न करें
DSTdaylight saving time; कुछ local days 23 या 25 घंटे के होते हैंtransition days को test करें

Real project में ये तीन rules AGENTS.md या CLAUDE.md में पहले लिखें।

  1. API में already happened event के timestamps ISO 8601 strings हों जिनमें Z या explicit offset हो।
  2. Future schedules में localDate, localTime, और timeZone अलग-अलग fields रहें।
  3. UI formatting में Intl.DateTimeFormat को हमेशा locale और timeZone दें; runtime default पर निर्भर न रहें।

Boundary को ऐसे सोचें।

flowchart LR
  A["Client: local date/time input"] --> B["API contract: localDate + localTime + timeZone"]
  B --> C["Server: validate and convert when needed"]
  C --> D["Database: instant in timestamptz + original timeZone"]
  D --> E["UI: format with Intl.DateTimeFormat"]
  E --> A

Intl.DateTimeFormat से safe base बनाएं

Display के लिए standard API Intl.DateTimeFormat से शुरू करें। MDN इसे language-sensitive date और time formatting की built-in API बताता है, और इसमें explicit timeZone दिया जा सकता है। Claude Code को साफ constraint दें: toLocaleString() बिना arguments के न use करे, और YYYY-MM-DD को local calendar date मानते हुए सीधे Date में parse न करे।

यह dependency-free module src/lib/date-policy.ts में रखें और UI, API, tests में reuse करें।

// src/lib/date-policy.ts
export const TIME_POLICY = {
  defaultLocale: 'hi-IN',
  defaultTimeZone: 'Asia/Kolkata',
} as const;

type FormatOptions = {
  locale?: string;
  timeZone?: string;
  includeWeekday?: boolean;
};

function toDate(input: string | Date): Date {
  const date = input instanceof Date ? input : new Date(input);

  if (!Number.isFinite(date.getTime())) {
    throw new Error(`Invalid date value: ${String(input)}`);
  }

  return date;
}

export function toUtcIso(input: string | Date): string {
  if (typeof input === 'string' && !/(Z|[+-]\d{2}:?\d{2})$/i.test(input)) {
    throw new Error('Timestamp must include Z or an explicit UTC offset.');
  }

  return toDate(input).toISOString();
}

function dateParts(date: Date, timeZone: string): Record<string, string> {
  const parts = new Intl.DateTimeFormat('en-US', {
    timeZone,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).formatToParts(date);

  return Object.fromEntries(
    parts
      .filter((part) => part.type !== 'literal')
      .map((part) => [part.type, part.value]),
  );
}

export function dayKeyInTimeZone(
  input: string | Date,
  timeZone = TIME_POLICY.defaultTimeZone,
): string {
  const parts = dateParts(toDate(input), timeZone);
  return `${parts.year}-${parts.month}-${parts.day}`;
}

export function formatInstant(
  input: string | Date,
  {
    locale = TIME_POLICY.defaultLocale,
    timeZone = TIME_POLICY.defaultTimeZone,
    includeWeekday = true,
  }: FormatOptions = {},
): string {
  return new Intl.DateTimeFormat(locale, {
    timeZone,
    weekday: includeWeekday ? 'short' : undefined,
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hourCycle: 'h23',
    timeZoneName: 'short',
  }).format(toDate(input));
}

मकसद हर date operation को utility में छिपाना नहीं है। मकसद instant, local-day key और display label को अलग करना है। Claude Code कोई नया helper जोड़ना चाहे, तो पहले उससे पूछें कि requirement इन तीन categories में किसकी है।

Future local time को explicit convert करें

Intl.DateTimeFormat output के लिए अच्छा है, लेकिन 2026-11-01 01:30 America/New_York जैसे local time को safe UTC instant में बदलने का सही tool नहीं है। Project में एक library चुनें और current official docs देखें। Luxon और उसके API docs explicit timezone APIs दिखाते हैं। date-fns focused date utilities के लिए अच्छा है, पर timezone needs को current docs से verify करें। Temporal TC39 में Stage 4 है, फिर भी target browser, Node support और polyfill policy तय करनी होगी।

Booking form में user local date और local time देता है; server उसे stored instant में convert करता है।

// src/lib/schedule-time.ts
import { DateTime } from 'luxon';

type LocalScheduleInput = {
  localDate: string; // YYYY-MM-DD
  localTime: string; // HH:mm
  timeZone: string; // IANA time zone, for example "America/New_York"
};

export function scheduleToUtcIso(input: LocalScheduleInput): string {
  const rawLocal = `${input.localDate}T${input.localTime}`;
  const local = DateTime.fromISO(rawLocal, { zone: input.timeZone });

  if (!local.isValid) {
    throw new Error(local.invalidExplanation ?? `Invalid local time: ${rawLocal}`);
  }

  const roundTrip = local.setZone(input.timeZone).toFormat("yyyy-MM-dd'T'HH:mm");
  if (roundTrip !== rawLocal) {
    throw new Error(`Nonexistent local time in ${input.timeZone}: ${rawLocal}`);
  }

  const iso = local.toUTC().toISO({ suppressMilliseconds: true });
  if (!iso) {
    throw new Error(`Could not convert local time to UTC: ${rawLocal}`);
  }

  return iso;
}

यह helper DST end पर repeat होने वाले 01:00 hour का पूरा product decision नहीं लेता। Product को तय करना होगा कि earlier offset लेना है, later offset लेना है, या user से confirm करना है। Claude Code से nonexistent local time, ambiguous local time, month end और leap day tests लिखवाएं।

Server, client और database boundaries अलग रखें

सबसे आम failure यह है कि कोई value Date में दे दी जाती है, बिना तय किए कि interpretation browser timezone की है या server timezone की। Browser input, API payload, DB column, email और CSV export अलग boundaries हैं।

Design review में कम से कम ये तीन use cases रखें।

  • Booking system: input venue की local time में, storage UTC instant में, display viewer या venue timezone में।
  • Billing cutoff: “month end 23:59” customer contract timezone की local date rule है; 24-hour chunks जोड़कर next month न बनाएं।
  • Support SLA: business days, holidays और office hours region-specific होते हैं; deadline instant और human-readable local context दोनों रखें।

PostgreSQL docs बताते हैं कि timestamp with time zone input UTC में convert होता है और original timezone retain नहीं होता। इसलिए timestamptz अकेला यह नहीं बताता कि user ने America/New_York चुना था। Product को जरूरत हो तो अलग column रखें।

create table scheduled_events (
  id uuid primary key,
  title text not null,
  starts_at timestamptz not null,
  original_time_zone text not null check (original_time_zone <> ''),
  local_date date not null,
  local_time time not null,
  created_at timestamptz not null default now()
);

create index scheduled_events_starts_at_idx
  on scheduled_events (starts_at);

यह assume न करें कि timestamp without time zone में 2026-06-02T09:00:00+09:00 डालने से offset meaningful रहेगा। PostgreSQL पहले type decide करता है; without time zone value में timezone indication ignore हो सकती है। Claude Code review checklist में “datetime column type API contract से match करता है?” जोड़ें।

DST और boundary tests fixed instant से लिखें

Tests को “today”, current clock या developer machine timezone पर depend नहीं करना चाहिए। Input को UTC instant के रूप में fix करें और expected local day या label assert करें। Vitest में शुरुआत इस file से करें। Advanced patterns के लिए Claude Code Vitest advanced देखें।

// src/lib/date-policy.test.ts
import { describe, expect, it } from 'vitest';
import { dayKeyInTimeZone, formatInstant, toUtcIso } from './date-policy';

describe('date/time policy', () => {
  it('requires an explicit offset for API timestamps', () => {
    expect(() => toUtcIso('2026-06-02T09:00:00')).toThrow(/offset/);
    expect(toUtcIso('2026-06-02T09:00:00+09:00')).toBe('2026-06-02T00:00:00.000Z');
  });

  it('calculates a local day key across the UTC date boundary', () => {
    expect(dayKeyInTimeZone('2026-03-31T15:01:00Z', 'Asia/Tokyo')).toBe('2026-04-01');
    expect(dayKeyInTimeZone('2026-04-01T00:30:00Z', 'America/Los_Angeles')).toBe('2026-03-31');
  });

  it('formats a DST transition instant in the requested time zone', () => {
    const label = formatInstant('2026-03-08T07:30:00Z', {
      locale: 'en-US',
      timeZone: 'America/New_York',
    });

    expect(label).toMatch(/03:30|3:30/);
    expect(label).toMatch(/EDT|GMT-4/);
  });
});

Test EDT या GMT-4 दोनों allow करता है क्योंकि CI environments में ICU data अलग हो सकता है। Local day key और UTC conversion business logic हैं, इसलिए उन्हें strict रखें।

Prompts और hooks से regression रोकें

Implementation से पहले Claude Code को constraints दें। लंबा prompt ठीक है अगर वह dangerous boundaries को साफ नाम देता है।

Before implementing date/time changes, read date-policy.ts and the database schema.

Constraints:
- API timestamps for completed events must be ISO strings with Z or an explicit offset
- Future bookings must keep localDate, localTime, and timeZone separate
- Intl.DateTimeFormat must always receive locale and timeZone
- Do not use new Date('YYYY-MM-DD') for local calendar dates
- Add Vitest cases for DST start, DST end, month end, and leap day
- Explain the PostgreSQL timestamp/timestamptz difference in the review notes

Done when:
- npm test -- --run date-time passes
- Updated API response examples are added to README

Team workflow में Claude Code hooks से edits के बाद deterministic tests चला सकते हैं। Official docs के अनुसार hooks Claude Code lifecycle events पर shell commands चला सकते हैं। पूरा workflow Claude Code hooks guide में देखें।

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npm test -- --run date-time"
          }
        ]
      }
    ]
  }
}

Date library सिर्फ popularity से न चुनें। Product किस तरह का time handle करता है, उस आधार पर चुनें। Intl.DateTimeFormat localized display के लिए, date-fns focused date utilities के लिए, Luxon IANA timezone scheduling के लिए, और Temporal Instant, PlainDate, ZonedDateTime जैसे clear types के लिए useful है। Temporal Stage 4 होने पर भी target runtime support और polyfill plan confirm करें।

OptionBest fitCaveat
IntlExplicit timezone के साथ localized displayLocal time को instant में convert करने का tool नहीं
date-fnsPure date math, function imports, small utilitiesTimezone needs के लिए official docs देखें
LuxonIANA timezone scheduling, relative time, ISO conversionDST ambiguous time के लिए product rule चाहिए
TemporalInstant, PlainDate, ZonedDateTime को अलग रखनाRuntime compatibility और polyfill जरूरी

Content monetization के हिसाब से generic library list कमजोर है। Reader को जानना होता है कि क्या save करें, conversion कहां करें और test क्या करें। अगर team इस policy को CLAUDE.md, hooks, PR review और migrations में embed करना चाहती है, तो Claude Code training और consulting अगला natural step है। Solo developers ऊपर वाला prompt free cheat sheet में जोड़कर repeatable guardrail बना सकते हैं।

Hands-on verification note

Masa की verification note: सबसे उपयोगी check था एक UTC instant fix करना, उसे Tokyo, New York और Los Angeles में format करना, और day boundary cross करते समय local date key assert करना। सबसे आसानी से reproduce होने वाला bug था YYYY-MM-DD को user local date मानकर Date में convert करना और दूसरे timezone में पिछला दिन दिखना। इस article की policy local dates को strings रखती है और सिर्फ stored instants तथा display labels को explicit convert करती है, इसलिए Claude Code के diffs review करना आसान हो जाता है।

#Claude Code #date time #timezone #Intl #testing
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.