Split a date string into day, month and year in C# and JavaScript
Given "25/12/2026", it is tempting to split on / and take the three parts. It works until the input arrives as 12/25/2026, 2026-12-25 or with a time attached. Parse the string into a date with an explicit format first; then day, month and year are properties.
C#: parse, then read the parts
using System.Globalization;
string input = "25/12/2026";
if (DateTime.TryParseExact(input, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out DateTime date))
{
int day = date.Day; // 25
int month = date.Month; // 12
int year = date.Year; // 2026
string monthName = date.ToString("MMMM", new CultureInfo("en-GB")); // "December"
DayOfWeek dow = date.DayOfWeek; // Friday
}
else
{
// not a valid date in that format: "31/02/2026" is rejected too
}
MMis the month andmmthe minutes; mixing them up is a classic bug.- Pass several accepted formats as an array:
new[] { "dd/MM/yyyy", "d/M/yyyy", "yyyy-MM-dd" }. - With
CultureInfo.InvariantCulture, the/in the format matches a literal slash. With another culture, it means "that culture's date separator", which may be a dot or a dash. - On .NET 6 and later,
DateOnly.TryParseExactrepresents a date without a time.
Why plain Split is fragile
string[] parts = input.Split('/');
int day = int.Parse(parts[0]); // works for "25/12/2026"...
// ...but gives day 12, month 25 for "12/25/2026", and throws for "2026-12-25"
Splitting gives you three numbers but no guarantee they form a date: 31/02/2026 splits happily. Parsing validates the date as a whole.
From a TextBox in Web Forms
An asp:TextBox with TextMode="Date" renders an HTML date input, which always posts yyyy-MM-dd regardless of how the browser displays it, so parse with that format:
DateTime.TryParseExact(txtBirth.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime birth);
For three separate drop-down lists (day, month, year), build the date with new DateTime(year, month, day) inside a try/catch for ArgumentOutOfRangeException, or check day <= DateTime.DaysInMonth(year, month) first.
JavaScript
function parseDmy(s) {
var m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(s.trim());
if (!m) return null;
var d = +m[1], mo = +m[2], y = +m[3];
var date = new Date(y, mo - 1, d); // months are 0-based in JavaScript
// reject 31/02 and similar, which Date silently rolls over into March
return date.getFullYear() === y && date.getMonth() === mo - 1 && date.getDate() === d ? date : null;
}
var dt = parseDmy("25/12/2026");
if (dt) console.log(dt.getDate(), dt.getMonth() + 1, dt.getFullYear()); // 25 12 2026
Splitting other strings into arrays is covered in Split a string into an array.
Official documentation
- Microsoft Learn: DateTime.TryParseExact, Custom date and time format strings, DateOnly
- MDN: Date