I have a date in the format of YYYY-MM-DD as a string (including the hyphens)

How do I split this string just to obtain YYYY, MM and DD separately? Possible use of an array or something?

Would really appreciate some help :)

Edit: Nevermind, just discovered the explode() function :P

Dani AI

Generated

A quick expert note tying the replies together: discovered explode() (a fine quick fix for well-formed input) and showed a low-level index/rindex style. For PHP, three idiomatic options work well depending on goals: use a DateTime parser for robust validation, a regex plus checkdate() for compact validation, or fixed-position substr() when the format is guaranteed. Examples and practical checks follow.

A robust, modern approach is to parse with DateTime and check for parse errors. DateTime::createFromFormat validates format and understands leap years. Example:

$date = trim($input); // 'YYYY-MM-DD'
$dt = DateTime::createFromFormat('Y-m-d', $date);
$errors = DateTime::getLastErrors();
if ($dt && $errors['warning_count'] === 0 && $errors['error_count'] === 0) {
    $year  = $dt->format('Y');
    $month = $dt->format('m');
    $day   = $dt->format('d');
} else {
    // invalid date string
}

See the DateTime docs: DateTime::createFromFormat and DateTime::getLastErrors.

A compact validated alternative uses a regex to capture groups and checkdate() to ensure month/day ranges:

if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $m) && checkdate((int)$m[2], (int)$m[3], (int)$m[1])) {
    $year = $m[1]; $month = $m[2]; $day = $m[3];
} else {
    // invalid
}

See preg_match and checkdate.

When input is strictly controlled and performance matters, fixed-position extraction is the fastest:

if (strlen($date) === 10 && $date[4] === '-' && $date[7] === '-') {
    $year  = substr($date, 0, 4);
    $month = substr($date, 5, 2);
    $day   = substr($date, 8, 2);
}

Always trim() incoming strings, verify length and delimiters, and validate the numeric ranges (use checkdate() or DateTime). For production code that must tolerate malformed input, prefer DateTime parsing; for quick scripts on trusted data, substring extraction is acceptable.

Use index and rindex functions as given here and a little string handling can serve your purpose.

#define ERROR(X) printf("%s Failed\n", X)


int main()
{

	char *month;
	char *year;
	char *date = "dd-mm-yy";

	month = index(date, '-');
	if (month == NULL)
		ERROR("index");
	
	year = rindex(date, '-');
	if(year == NULL)
		ERROR("rindex");

	printf("date = %s month = %s yeat = %s\n", date, month, year);
	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.