Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i convert a date in php to SQL format ? (and insert it)

Tags:

sql

php

datetime

I'm trying to insert a date , lets say CURDATE() to an sql DateTime field.

My date is in the format of: 28/01/2008

When I try to insert it to the SQL, I get just zeroes.

So how can I convert it properly?

like image 360
Yochai Timmer Avatar asked Jan 25 '11 08:01

Yochai Timmer


People also ask

How can I change the date format in PHP?

Change YYYY-MM-DD to DD-MM-YYYY In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ".

How can I get current date in YYYY-MM-DD format in PHP?

$date = date("yyyy-mm-dd", strtotime(now));


4 Answers

$new_date = date('Y-m-d', strtotime($old_date));

Explanation

  1. strtotime() will try to parse a string ($old_date in this case) and understand what date it is. It expects to be given a string containing an English date format or English textual datetime description. On success it will return a Unix timestamp (the number of seconds since January 1 1970). Now we have got a point in time out of that string.

  2. date() then will turn this previously obtained point in time to a format, described in the first parameter, in the example above it is the 'Y-m-d'

    • Y — A full numeric representation of a year, 4 digits
    • m — Numeric representation of a month, with leading zeros
    • d — Day of the month, 2 digits with leading zeros
    • - — literally the minus symbol

Here's a full list of characters you can use in the format parameter string

like image 137
Dan Grossman Avatar answered Oct 06 '22 02:10

Dan Grossman


I'm trying to insert a date , lets say CURDATE() to an sql DateTime field.

$timestamp = strtotime($old_date);
$mydate = date('Y-m-d H:i:s', $timestamp);
like image 44
Sarfraz Avatar answered Oct 06 '22 01:10

Sarfraz


Since you're using the European date notation (dd/mm/yyyy) the strtotime function will return 0 (which in turn will be converted to 1970-01-01 by date) if you don't use - or . as separator.

So if you want to use strtotime, then you will have to change your date strings just a bit :

$olddate = '28/01/2008';
$newdate = strtotime(str_replace('/', '-', $olddate));

$newdate should now contain '2008-01-28'...

like image 26
wimvds Avatar answered Oct 06 '22 01:10

wimvds


join('-',array_reverse(explode('/',$date)))

to get the standard YYYY-MM-DD Mysql date format.

or just use MySQL' DATE_FORMAT

like image 28
MatTheCat Avatar answered Oct 06 '22 01:10

MatTheCat