datetime-timezone
БесплатноБез исполняемых скриптовНе проверенHandle datetime and timezone conversions correctly across frontend, API, and database. Use this skill when working with datetime-local inputs, scheduling…
от mjunaidca★ 27 звёзд на GitHubОб этом скилле
DateTime and Timezone Handling
Correctly handle datetime values across the full stack: browser → API → database → back to browser.
When to Use
- Implementing due dates, reminders, or scheduling features
- Working with
datetime-localHTML inputs - Storing timestamps in PostgreSQL/databases
- Displaying times in user's local timezone
- Debugging "wrong time" issues
The Golden Rule
Store UTC, Display Local
Browser (local) → Convert to UTC → API → Store UTC → Database
Database → Return UTC → API → Browser → Display in local
Critical Pitfall: datetime-local Input
The HTML <input type="datetime-local"> returns a string WITHOUT timezone info:
<input type="datetime-local" value="2025-12-15T23:13">
This gives you "2025-12-15T23:13" - but is this UTC? Local time? The browser doesn't tell you.
The Bug
// WRONG - Backend interprets as UTC, but user entered local time!
const dueDate = "2025-12-15T23:13" // User in PKT (UTC+5)
await api.createTask({ due_date: dueDate })
// Backend stores as 23:13 UTC
// But user meant 23:13 PKT = 18:13 UTC
// Task is now 5 hours late!
The Fix
// CORRECT - Convert local datetime to UTC ISO string
function handleSubmit() {
let dueDateUTC: string | undefined = undefined
if (dueDate) {
// datetime-local gives "2025-12-15T23:13" (local time, no TZ)
// new Date() interprets it in browser's local timezone
// toISOString() converts to UTC: "2025-12-15T18:13:00.000Z"
const localDate = new Date(dueDate)
dueDateUTC = localDate.toISOString()
}
await api.createTask({ due_date: dueDateUTC })
}
Frontend Patterns (TypeScript/React)
Converting datetime-local to UTC
// Input: "2025-12-15T23:13" (from datetime-local)
// Output: "2025-12-15T18:13:00.000Z" (UTC ISO string)
function localToUTC(localDatetime: string): string {
const date = new Date(localDatetime)
return date.toISOString()
}
Converting UTC to datetime-local (for editing)
// Input: "2025-12-15T18:13:00Z" (UTC from API)
// Output: "2025-12-15T23:13" (local, for datetime-local input)
function utcToLocal(utcDatetime: string): string {
const date = new Date(utcDatetime)
// Format: YYYY-MM-DDTHH:MM (no seconds, no Z)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${year}-${month}-${day}T${hours}:${minutes}`
}
Full Form Example (React)
"use client"
import { useState } from "react"
export function TaskForm() {
const [dueDate, setDueDate] = useState("") // Local datetime string
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
// Convert local to UTC for API
let dueDateUTC: string | undefined
if (dueDate) {
dueDateUTC = new Date(dueDate).toISOString()
}
await api.createTask({
title: "My Task",
due_date: dueDateUTC, // UTC ISO string
})
}
return (
<form onSubmit={handleSubmit}>
<input
type="datetime-local"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
/>
<button type="submit">Create</button>
</form>
)
}
Editing Existing Task
"use client"
import { useState, useEffect } from "react"
export function EditTaskForm({ task }: { task: Task }) {
const [dueDate, setDueDate] = useState("")
useEffect(() => {
// Convert UTC from API to local for input
if (task.due_date) {
setDueDate(utcToLocal(task.due_date))
}
}, [task])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
// Convert back to UTC for API
const dueDateUTC = dueDate ? new Date(dueDate).toISOString() : undefined
await api.updateTask(task.id, { due_date: dueDateUTC })
}
return (
<input
type="datetime-local"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
/>
)
}
Backend Patterns (Python/FastAPI)
Pydantic Model with Timezone Normalization
from datetime import UTC, datetime
from pydantic import field_validator
from sqlmodel import SQLModel
class TaskCreate(SQLModel):
title: str
due_date: datetime | None = None
@field_validator("due_date", mode="after")
@classmethod
def normalize_datetime(cls, v: datetime | None) -> datetime | None:
"""Convert timezone-aware to naive UTC for storage."""
if v is None:
return None
# If timezone-aware, convert to UTC and strip timezone
if v.tzinfo is not None:
v = v.astimezone(UTC).replace(tzinfo=None)
return v
API Endpoint
@router.post("/tasks", response_model=TaskRead)
async def create_task(
task_in: TaskCreate,
session: AsyncSess
Установить datetime-timezone в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл datetime-timezone?
Handle datetime and timezone conversions correctly across frontend, API, and database. Use this skill when working with datetime-local inputs, scheduling features, due dates, reminders, or any time-sensitive functionality. Covers the critical pitfall of browser datetime-local inputs lacking timezone info.
Как установить скилл datetime-timezone?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл datetime-timezone запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic