-4

I have three variables:

1.) $year (e.g. "2018"),

2.) $month (e.g. "9" or "12"),

3.) $day (e.g. "5" or "21").

I want to merge them into one single variable ($date) in the format of YYYY-mm-dd, i.e. "2018-09-14".

Note that the month "9" and the day "5" now have "0" in front of them.

What would be the best way to do so?

Thank you!

anmipa
  • 93
  • 1
  • 8

2 Answers2

1

You can just:

$year = 1980;
$month = 9;
$day = 5;

$date = strftime("%F", strtotime($year."-".$month."-".$day));

But why not just concatenate the strings?

$date = $year . "-" . str_pad($month, 2, "0", STR_PAD_LEFT) . "-" . str_pad($day, 2, "0", STR_PAD_LEFT);
Omagerio
  • 495
  • 2
  • 11
0
echo date("d-m-Y",mktime(0, 0, 0, $day, $month, $year)); 
  • 1
    Notice that the OP asked for a different format from what you are providing in your answer. An explanation on why this is better than simple string concatenation would improve your answer. – CPHPython Sep 14 '18 at 10:38