How do you format and convert a DateTime value to VarChar in SQL Server? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you format and convert a DateTime value to VarChar in SQL Server?

message-square
0

To format and convert a DATETIME (or DATETIME2) value to VARCHAR in SQL Server (T-SQL), use CONVERT(VARCHAR(length), value, style_code) for fast, deterministic standard formats, or FORMAT(value, ‘pattern’) for custom patterns (with higher CPU cost on large sets). Always specify an explicit VARCHAR(n) length so output is not truncated.

  1. Fast Standard Formats: CONVERT(VARCHAR(n), dt, style) CONVERT uses built-in style codes—great for high-volume T-SQL queries and unambiguous date strings:

SQL DECLARE @dt DATETIME2(3) = ‘2026-11-30 18:19:45.123’;

SELECT CONVERT(VARCHAR(10), @dt, 23) AS iso_date_yyyy_mm_dd, – ‘2026-11-30’ CONVERT(VARCHAR(19), @dt, 120) AS odbc_canonical_24h, – ‘2026-11-30 18:19:45’ CONVERT(VARCHAR(23), @dt, 121) AS odbc_with_ms, – ‘2026-11-30 18:19:45.123’ CONVERT(VARCHAR(10), @dt, 103) AS british_dd_mm_yyyy, – ‘30/11/2026’ CONVERT(VARCHAR(10), @dt, 101) AS us_mm_dd_yyyy; – ‘11/30/2026’ 23: YYYY-MM-DD

120: YYYY-MM-DD HH:MI:SS (24-hour)

121: YYYY-MM-DD HH:MI:SS.mmm

103 / 101: DD/MM/YYYY vs. MM/DD/YYYY (avoid ambiguous slash formats for sorting or interchange).

  1. Custom Patterns: FORMAT(dt, ‘pattern’) Use FORMAT() when you need custom layout patterns (such as 12-hour clock with tt, month names, or custom separators):

SQL DECLARE @dt DATETIME2 = ‘2026-11-30 18:19:45’;

SELECT FORMAT(@dt, ‘yyyy-MM-dd’) AS ymd_dash, – ‘2026-11-30’ FORMAT(@dt, ‘yyyy-MM-dd HH:mm’) AS ymd_hm_24h, – ‘2026-11-30 18:19’ FORMAT(@dt, ‘dd MMM yyyy hh:mm tt’) AS readable; – ‘30 Nov 2026 06:19 PM’ MM = two-digit month (01–12); mm = two-digit minute (00–59).

HH = 24-hour (00–23); hh = 12-hour (01–12) paired with tt (AM/PM).

FORMAT() relies on CLR formatting and is noticeably slower than CONVERT() across millions of rows.

  1. Operational Checklist Always size VARCHAR(n) explicitly (VARCHAR(10) for YYYY-MM-DD, VARCHAR(19) for YYYY-MM-DD HH:MI:SS, etc.) to prevent truncation.

Prefer CONVERT with style 23 or 120 in batch/production T-SQL when standard formats fit, reserving FORMAT() for display or custom strings on smaller sets.

Keep columns typed as DATE / DATETIME2 for filtering and sorting—only convert to VARCHAR in the final projection or presentation layer.

Account for NULLs: both CONVERT and FORMAT return NULL when given a NULL datetime input.