Insert DATE and DATETIME Values in MySQL

MySQL stores calendar dates in DATE columns and date-plus-time values in DATETIME or TIMESTAMP columns. Insert values in a format MySQL can interpret for the target datatype.

INSERT INTO dt_tb (dt, dt2)
VALUES (
    '2026-09-09 10:52:00',
    '2026-09-09'
);

In this example, dt is a DATETIME column and dt2 is a DATE column.

For the current MySQL date and time, you usually do not need PHP to format them first. Use NOW() for date + time and CURDATE() for the date.
Insert date and datetime values into MySQL

DATE and DATETIME Formats Top ↑

A MySQL DATE value is normally written as:

'YYYY-MM-DD'

Example:

'2026-09-09'

A MySQL DATETIME value is normally written as:

'YYYY-MM-DD HH:MM:SS'

Example:

'2026-09-09 10:52:00'
The format shown here is the SQL representation sent to MySQL. Your application can display dates in another format without storing them as formatted text.

Modern Sample Table Top ↑

The previous version of this tutorial used zero dates such as '0000-00-00' and repeated three UNIQUE indexes on the same id column. Those definitions are unnecessary and can conflict with modern strict SQL modes.

Use a normal primary key and real DATE/DATETIME columns:

CREATE TABLE dt_tb (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    dt DATETIME NOT NULL,
    dt2 DATE NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB
  DEFAULT CHARSET=utf8mb4;

See CREATE TABLE for column, key, and datatype design.

Insert Fixed Date Values Top ↑

INSERT INTO dt_tb (dt, dt2)
VALUES (
    '2004-05-05 23:56:25',
    '2005-06-12'
);

The values match the datatypes:

  • dt receives a DATETIME value.
  • dt2 receives a DATE value.

Insert the Current Date and Time Top ↑

When MySQL itself should supply the current values, use NOW() and CURDATE():

INSERT INTO dt_tb (dt, dt2)
VALUES (
    NOW(),
    CURDATE()
);

This is simpler than calculating the same current values in PHP and concatenating them into SQL.

NOW() uses the MySQL session time zone and returns date + time. CURDATE() returns only the current MySQL session date.

Insert PHP Date Values with PDO Top ↑

Sometimes the application deliberately supplies the date, for example because it uses a specific application time zone or receives a validated date from another system.

Format the PHP values, then bind them with PDO rather than concatenating them into SQL:

<?php
require "config.php";

$now=new DateTimeImmutable(
    'now',
    new DateTimeZone('Asia/Kolkata')
);

$dt=$now->format('Y-m-d H:i:s');
$dt2=$now->format('Y-m-d');

$sql="INSERT INTO dt_tb (dt, dt2)
      VALUES (:dt, :dt2)";

try{
    $stmt=$dbo->prepare($sql);
    $stmt->bindValue(':dt', $dt, PDO::PARAM_STR);
    $stmt->bindValue(':dt2', $dt2, PDO::PARAM_STR);
    $stmt->execute();
    echo 'Date values stored.';
}catch(PDOException $e){
    error_log($e->getMessage());
    echo 'Unable to store the date values.';
}

See PDO connection and PDO INSERT.

The old example inserted PHP variables by directly placing them inside the SQL string. Prepared statements are the safer default when application values are being inserted.

PHP Time Zone vs MySQL Time Zone Top ↑

If PHP generates the date while MySQL generates other timestamps, confirm that both use the intended time zone.

PHP:

$now=new DateTimeImmutable(
    'now',
    new DateTimeZone('Asia/Kolkata')
);

MySQL session:

SELECT @@session.time_zone;

A mismatch can make "current" dates differ around midnight or can shift date-time values relative to application expectations.

Insert User-entered Dates Safely Top ↑

If a form supplies a date such as 09/09/2026, do not insert the raw text directly into a DATE column. Parse and validate it first.

PHP can convert an expected input format to the MySQL format:

<?php
$input='09/09/2026';

$date=DateTimeImmutable::createFromFormat(
    'd/m/Y',
    $input
);

if($date === false){
    echo 'Invalid date.';
}else{
    $mysql_date=$date->format('Y-m-d');
}

See PHP createFromFormat() for date parsing examples.

For strict validation, also inspect parsing warnings/errors when user input can contain impossible dates such as 31/02/2026. A successful-looking conversion should not silently normalize invalid input into another date.

Convert Other Date Formats with STR_TO_DATE() Top ↑

MySQL's STR_TO_DATE() can parse text when the input format is known:

INSERT INTO dt_tb (dt, dt2)
VALUES (
    STR_TO_DATE(
        '09-09-2026 10:52:00',
        '%d-%m-%Y %H:%i:%s'
    ),
    STR_TO_DATE(
        '09-09-2026',
        '%d-%m-%Y'
    )
);

This is useful when the source text uses a known external format. For application form data, parsing and validating in the application layer can make validation rules easier to control.

Automatic Current Timestamp Top ↑

If a column should always record the insertion time, define that behavior in the table instead of supplying the value in every INSERT:

CREATE TABLE event_log (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    event_name VARCHAR(100) NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB
  DEFAULT CHARSET=utf8mb4;

Then the INSERT can omit created_at:

INSERT INTO event_log (event_name)
VALUES ('User login');

Automatically Store the Last Update Time Top ↑

A separate column can track when a row was last modified:

CREATE TABLE article (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    title VARCHAR(150) NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL
        DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);

See automatic insertion and update timestamps.

NULL and Missing Dates Top ↑

If "no date has been assigned yet" is a valid state, model that with NULL rather than a fake zero date.

CREATE TABLE task (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    due_date DATE NULL,
    PRIMARY KEY (id)
);

Insert a missing date as NULL:

INSERT INTO task (due_date)
VALUES (NULL);

See SQL NULL values.

Invalid Dates and Strict SQL Mode Top ↑

Modern MySQL configurations commonly use strict SQL modes. Invalid dates can be rejected instead of silently becoming zero dates or unexpected values.

Examples that should not be used as normal application dates:

'0000-00-00'
'0000-00-00 00:00:00'
'2026-02-31'
Do not use zero dates as placeholders. Use NULL for an absent date when the schema permits it, or require a valid date when the field is mandatory.

Common Date-insert Mistakes Top ↑

Reversing the DATE and DATETIME columns Top ↑

Know which destination column expects only a date and which expects date + time.

Concatenating PHP values directly into SQL Top ↑

Use prepared statements for application-provided values.

Using zero dates as defaults Top ↑

They are poor placeholders and can be rejected by strict SQL modes.

Creating duplicate UNIQUE indexes on the same ID Top ↑

One PRIMARY KEY on an AUTO_INCREMENT ID is normally enough for row identity. Add other indexes only for real constraints or query needs.

Using PHP date() when MySQL should own the current timestamp Top ↑

For database-created timestamps, NOW(), CURDATE(), or a column default can be simpler and more consistent.

Ignoring time zones Top ↑

PHP and MySQL can produce different "current" values if they use different zones.

Storing display-formatted dates in VARCHAR columns Top ↑

Use proper DATE/DATETIME/TIMESTAMP datatypes, then format values for display.

Video Tutorial Top ↑

INSERTING PHP Current Date and time to MySQL table using YYYY-mm-dd format and STR_TO_DATE()

Frequently Asked Questions Top ↑

Q1: What format should I use for a MySQL DATE value?

Use a valid date such as YYYY-MM-DD, for example 2026-09-09.

Q2: What format should I use for a MySQL DATETIME value?

Use a valid date and time such as YYYY-MM-DD HH:MM:SS, for example 2026-09-09 10:52:00.

Q3: How do I insert the current MySQL date and time?

Use NOW() for the current date and time and CURDATE() for the current date.

Q4: Should I insert PHP date variables by concatenating them into SQL?

No. Bind application values with a prepared PDO statement instead of concatenating them into the SQL string.

Q5: Should I use 0000-00-00 when a date is missing?

No. Use NULL if a missing date is a valid state, or require a valid date when the field is mandatory.

Q6: How can I insert a date entered as DD-MM-YYYY?

Parse and validate it in the application or use STR_TO_DATE() with the matching format string before storing it as a real DATE value.

Q7: Can MySQL automatically store the insertion time?

Yes. A DATETIME or TIMESTAMP column can use DEFAULT CURRENT_TIMESTAMP so the value is populated automatically when a row is inserted.


CURDATE() Comparison Operators SQL Date References


Subscribe to our YouTube Channel here



plus2net.com
Puneet Verma

31-12-2009

Is there a way to provide condition check while using INSERT in sql querry
John

03-02-2010

Sorry, but I can't get it to work. Why don't you include this as part of a practical database example. I've been all over the net just to stick a date field in my database. Nothing works - it can't be that hard to do a practial working example of this.
Matt McCarty

25-04-2010

@John... I have a variable list (one is a date to insert, i.e. $dtCreated=date('Y-m-d'); Then I have my INSERT statement with that variable (using PHP) $query = "INSERT INTO myTable VALUES ('$dtCreated')"; If you have more than one variable, order matters!
chan

20-08-2010

I need aprocedure which generates a table with columns week,start_dt,End_dt. Week should have all 52 weeks,start_dt should every weeks start day ,end_dt should have everyweeks end date. Please help Thanks
madhavi

24-04-2014

I need to alter table with current date and time in mysql
smo

14-11-2014

One practical example using PHP is added to this tutorial.
sadia

24-08-2015

Very helpful
deepa

30-05-2016

insted of php code i want html or javascript code..can u give us>
Shital Gamaji Patil

05-01-2017

how to add from and to date in a single column. or in single column how to add two dates.
smo1234

19-02-2017

You can store dates as string in a single column. You can use any delimiter to separate the dates, while retrieving you can use the same delimiter to separate them. But what is the problem in storing them in two different columns ?




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer