-3

I have a column in a MySQL table that is of type 'datetime'. How do I get a value from php of the current date and time with the format - for example: "2014-11-09 15:06:51" and set into a variable?

thanks.

johnnyX
  • 75
  • 1
  • 7
  • possible duplicate of [NOW() function in PHP](http://stackoverflow.com/questions/1995562/now-function-in-php) – vascowhite Nov 16 '14 at 08:07

3 Answers3

0

check this PHP documentation for more clarification.

$DateTime = date('Y-m-d H:i:s');

Ref

Community
  • 1
  • 1
Zeeshan
  • 1,659
  • 13
  • 17
0

You can use CURDATE() of MySql. No need of using php for this.

INSERT INTO  `db`.`data1` (
`id` ,
`date`
)
VALUES (
'2', CURDATE()
)

See for more documentation http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate

user7282
  • 5,106
  • 9
  • 41
  • 72
0

Well if you're doing this in a class you could use my DateTime getter and setter. Assumes that $this->Date is a php DateTime object and you're using mysql with a DATETIME column.

Here's what using it looks like:

$this->setDate($whatever_date); // give it a timestamp, mysql DATETIME, or anything that can be read by strtotime()

// Need to put the date into mysql? Use this:
$this->getDate('mysql');

// Need to get the date so a person can read it? 
$this->getDate('human');

// want it as a timestamp?
$this->getDate('unix');

Here's the methods:

// accepts 'human', 'mysql', 'unix', or custom date() string
function getDate($format='human'){

    if(get_class($this->Date)!='DateTime') return FALSE;


    try{

        switch ($format) {
            case 'human':
                return $this->Date->format('M j, Y g:i a'); // Show date and time
                // return $this->Date->format('M j, Y'); // Just the date
                break;

            case 'mysql':
                return $this->Date->format('Y-m-d H:i:s');
                break;

            case 'unix':
                return $this->Date->format('U'); // may return a negative number for old dates
                break;

            default:
                return $this->Date->format($format);
                break;
        }

    } catch (Exception $e){
        throw new Exception('Can not use that format for getting DateTime');
        return FALSE;
    }
}

// Sets as a DateTime object - accepts either a timestamp or a date() string
function setDate($date){
    try{

        if(is_numeric($date) && (int)$date==$date){ // timestamp
            $this->Date = new DateTime(date('F j, Y, g:i a', $date));
        } else {
            $this->Date = new DateTime($date);
        }


    } catch (Exception $e){
        throw new Exception('Can not set the given value ('.$date.') as DateTime');
        return FALSE;
    }
    return TRUE;
}

If you're not using classes you would want to combine them into a single function that takes the format you have and returns the format you need.

Syntax Error
  • 4,475
  • 2
  • 22
  • 33