954,580 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help with Date Format

Hey everyone,

I have the following varaibles:

$_POST['month']
$_POST['day']
$_POST['year']

I need them to be put into a string format such as '2012-02-15' (Year-Month-Day).

Could someone please help me do this in php?

I've tried a few times but can't connect them with the "-" successfully.

Thanks for your help.

bbman
Junior Poster
182 posts since May 2010
Reputation Points: 22
Solved Threads: 10
 
<?php
if(isset($_POST['month']) && isset($_POST['day']) && isset($_POST['year']) && is_int($_POST['month']) && is_int($_POST['day']) && is_int($_POST['year']) && $_POST['month'] > 0 && $_POST['month'] < 13 && $_POST['day'] > 0 && $_POST['day'] < 32 && $_POST['year'] > 0 && $_POST['year'] < 2020){
  if(checkdate($_POST['month'],$_POST['day'],$_POST['year'])){
    $date = "{$_POST['year']}-{$_POST['month']}-{$_POST['day']}";
  }else{
    echo "This date does not exist";
  }
}else{
  echo "Date data not valid";
} 


?>


That's just a little clunky - and you could create nicer tests, e.g. stipulating better limits for the year. There are loads of ways to do it. You could use mktime() and date(), or even use the DateTime object.

diafol
Rhod Gilbert Fan (ardav)
Moderator
7,792 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 

$date = "{$_POST['year']}-{$_POST['month']}-{$_POST['day']}";

Thank you so much. This was the line I needed. I wrote similar lines several times but they just didnt work.

I appreciate your help, keep up the good work :D

bbman
Junior Poster
182 posts since May 2010
Reputation Points: 22
Solved Threads: 10
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: