1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Date Explained: Format, Parse and Avoid Timezone Bugs

The JavaScript Date object stores one moment in time, but zero-based months, local vs UTC methods and string parsing cause classic off-by-one bugs. Learn how Date really works, how to parse and format safely with Intl, and how to do date math, with output from tested Node.js runs.

9 min read
JavaScript Date: format, parse and avoid timezone bugs

Key takeaways

  • A JavaScript Date is a single number: milliseconds since 1 January 1970 UTC. Time zones only matter when you read or write it.
  • Months run from 0 to 11. new Date(2026, 10, 17) is 17 November.
  • new Date("2026-11-17") is parsed as UTC midnight. In our New York test it displayed as 16 November.
  • Format for people with toLocaleString or Intl.DateTimeFormat, and for machines with toISOString().

A user in New York picks 17 November on a form, and the confirmation page says 16 November. A report built at midnight lands in the wrong month. These bugs come from the JavaScript Date object, which is famous for surprising behaviour. Once you know how it stores time and which methods use which zone, the surprises go away.

We ran every example with Node.js 24.22.1. To make results repeatable, most runs set the process time zone to UTC with process.env.TZ. Where the zone matters, we ran the same code under New York and Kolkata time and show both.

What a Date actually stores

Internally a Date holds one number: the milliseconds since the Unix epoch, 1 January 1970 at 00:00 UTC. It has no time zone of its own. Methods such as getHours() translate that number into the local zone of the machine running the code, while getUTCHours() uses UTC. The same Date can therefore print differently on a server and in a browser. Our Unix timestamp guide explains the epoch in depth.

Creating dates

new Date()                        // now
new Date(1794873600000)           // from milliseconds since the epoch
new Date("2026-11-17T09:30:00Z")  // from an ISO string
new Date(2026, 10, 17, 9, 30)     // from parts, in LOCAL time
new Date(Date.UTC(2026, 10, 17))  // from parts, in UTC

Date.now() returns the current time as a number of milliseconds, which is handy for timing. It is 13 digits long today, as our run confirmed. Date.UTC() also returns a number, so wrap it in new Date() when you need a Date object.

Zero-based months (and day overflow)

const d = new Date(2026, 10, 17, 9, 30);
console.log(d.toISOString(), d.getMonth(), d.getDay(), d.getDate());
// 2026-11-17T09:30:00.000Z 10 2 17

Month index 10 is November. getDay() returns the weekday (2 means Tuesday, with Sunday as 0), and getDate() returns the day of the month. Mixing up getDay and getDate is the second most common Date bug after months.

Out-of-range values do not raise errors. They roll over silently:

new Date(2026, 1, 30).toISOString().slice(0, 10)
// 2026-03-02

“30 February” became 2 March. That is useful for date math, but it means invalid user input will not be caught. Validate the parts yourself if you build dates from form fields.

The string parsing trap

This is the bug behind most “off by one day” reports. A date-only ISO string is treated as UTC, but a date-time string without a zone is treated as local. We ran the same line under two zones:

const d = new Date("2026-11-17");
console.log(d.getDate(), d.toString().slice(0, 15));
Time zone getDate() Displayed new Date(“2026-11-17T00:00”)
America/New_York 16 Mon Nov 16 2026 2026-11-17T05:00:00.000Z
Asia/Kolkata 17 Tue Nov 17 2026 2026-11-16T18:30:00.000Z

In New York, UTC midnight on the 17th is still the evening of the 16th, so the local display shows the wrong day. Users west of Greenwich see the bug; developers east of it often never notice. The fixes:

  • For a calendar date with no time, such as a birthday, keep it as the string "2026-11-17" or build it with new Date(2026, 10, 17) in local time.
  • For a moment in time, always include the zone: "2026-11-17T09:30:00Z" or "...+05:30".
  • Never parse formats such as "17/11/2026". Our run returned NaN for it, and other engines may guess differently.

Invalid dates

console.log(String(new Date("nope")), isNaN(new Date("nope")));
// Invalid Date true

A failed parse does not throw. It returns a Date whose time value is NaN. Check with isNaN(d) or Number.isNaN(d.getTime()) before using user-supplied dates. Calling toISOString() on an invalid date throws a RangeError, which often surfaces far from the original input.

Local vs UTC methods

Almost every getter and setter comes in two versions: getHours() and getUTCHours(), setDate() and setUTCDate(), and so on. Pick one family per task and stick with it. Server code that stores and compares times is usually simplest in UTC. Code that shows times to a person should format in their zone.

getTimezoneOffset and its backwards sign

new Date(2026, 10, 17).getTimezoneOffset()
// UTC: 0   America/New_York: 300   Asia/Kolkata: -330

The result is in minutes, and the sign is the reverse of how offsets are usually written. New York is UTC−5, yet the method returns +300. Kolkata is UTC+5:30 and returns −330. The value can also change during the year because of daylight saving, so always ask for the offset of the specific date you care about.

Formatting dates

For machines, use ISO 8601. toISOString() always outputs UTC with a Z:

new Date(Date.UTC(2026, 10, 17, 4, 0)).toISOString()
// 2026-11-17T04:00:00.000Z

For a custom fixed format, build it from parts and pad with padStart:

const pad = n => String(n).padStart(2, "0");
const f = new Date(Date.UTC(2026, 10, 7, 5, 4));
console.log(`${f.getUTCFullYear()}-${pad(f.getUTCMonth() + 1)}-${pad(f.getUTCDate())} ${pad(f.getUTCHours())}:${pad(f.getUTCMinutes())}`);
// 2026-11-07 05:04

Remember the + 1 on the month. Our JavaScript tutorial covers template literals if the syntax is new.

Formatting for people with Intl

For anything a person reads, let the built-in Intl API handle language, order and time zone:

const x = new Date(Date.UTC(2026, 10, 17, 4, 0));
x.toLocaleDateString("en-GB", { timeZone: "UTC" })   // 17/11/2026
x.toLocaleDateString("en-US", { timeZone: "UTC" })   // 11/17/2026
x.toLocaleString("en-IN", { timeZone: "Asia/Kolkata", dateStyle: "medium", timeStyle: "short" })
// 17 Nov 2026, 9:30 am
x.toLocaleString("en-US", { timeZone: "America/New_York", dateStyle: "full", timeStyle: "long" })
// Monday, November 16, 2026 at 11:00:00 PM EST
new Intl.DateTimeFormat("de-DE", { weekday: "long", day: "numeric", month: "long", timeZone: "UTC" }).format(x)
// Dienstag, 17. November

The same instant appears as Tuesday morning in India and Monday night in New York, correctly, because we named the zone. Always pass timeZone when the viewer’s zone is known. Intl.RelativeTimeFormat handles phrases: our run produced “yesterday” for -1, "day" with numeric: "auto", and “in 3 weeks” for 3, "week".

Date math

const a = new Date(Date.UTC(2026, 10, 17));
const b = new Date(Date.UTC(2026, 11, 25));
console.log((b - a) / 86400000);   // 38 days

const e = new Date(Date.UTC(2026, 10, 17));
e.setUTCDate(e.getUTCDate() + 45);
console.log(e.toISOString().slice(0, 10));   // 2027-01-01

Subtracting Dates gives milliseconds; divide by 86,400,000 for days. Adding days with setUTCDate rolls across months and years correctly. Adding months needs care:

const c = new Date(Date.UTC(2026, 0, 31));
c.setUTCMonth(c.getUTCMonth() + 1);
console.log(c.toISOString().slice(0, 10));   // 2026-03-03

“31 January plus one month” overflowed past February into 3 March. Decide your business rule, usually “clamp to the last day of the month”, and code it explicitly. Doing day math in local time across a daylight saving change can also give 23 or 25 hour days, so prefer UTC methods for arithmetic.

Comparing dates

console.log(a < b, a == new Date(a), a.getTime() === new Date(a).getTime());
// true false true

< and > work because they convert Dates to numbers. But == and === compare object identity, so two Dates for the same instant are “not equal”. Compare getTime() values instead. In tests, assert on toISOString() strings for readable failure messages.

Dates are mutable

const shared = new Date(Date.UTC(2026, 10, 17));
const copy = shared;
copy.setUTCFullYear(2030);
console.log(shared.getUTCFullYear());   // 2030

Assignment does not copy a Date, and setters change it in place. A function that “adds a day” to a Date passed in will change the caller’s object too. Make a real copy with new Date(d) or new Date(d.getTime()) before modifying.

Dates in JSON

JSON.stringify({ at: x })                         // {"at":"2026-11-17T04:00:00.000Z"}
typeof JSON.parse(JSON.stringify({ at: x })).at   // 'string'

Dates serialise to ISO strings, but parsing does not turn them back into Dates. Convert known date fields with new Date(value) after JSON.parse, or use a reviver function. Our Fetch API guide shows where this comes up with API responses.

Temporal and date libraries

The Temporal API is a modern replacement with separate types for plain dates, zoned date-times and durations. It was undefined in our Node.js 24.22.1 run, so check your target runtimes before using it. Until it is everywhere, small libraries such as date-fns and Luxon cover formatting, parsing and time zones with clearer APIs. For simple needs, the built-in Date plus Intl, used carefully as above, is enough.

Final thoughts

The JavaScript Date is less mysterious once you see it as a single UTC timestamp with local and UTC views. Remember the zero-based months, never trust date-only strings for local dates, pass timeZone when formatting, do arithmetic with UTC methods, compare with getTime(), and copy before you mutate. Add a test that runs in a zone west of UTC, and the off-by-one-day bug will never reach your users.

FAQ

Why is my JavaScript date one day off?

A date-only string such as 2026-11-17 is parsed as UTC midnight. In time zones west of UTC that is still the previous day locally. Build local dates from parts instead.

Why does getMonth return the wrong month?

JavaScript months are zero-based, so January is 0 and December is 11. Add one when displaying the month number.

How do I format a date as YYYY-MM-DD in JavaScript?

Use toISOString and take the first ten characters for a UTC date, or build the string from getFullYear, getMonth plus one and getDate with padStart for a local date.

How do I compare two dates in JavaScript?

Use less than or greater than for ordering. For equality compare the getTime values, because double and triple equals compare object identity.

How do I get the current timestamp in JavaScript?

Date.now returns milliseconds since 1 January 1970 UTC. Divide by 1000 and round down if an API expects seconds.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →