Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert date string to mysql datetime field

Tags:

php

mysql

I have a bunch of records with dates formatted as a string such as '04/17/2009'

I want to convert them to a mysql datetime field

I plan to use a foreach loop to read the old date value and insert the newly formatted value into a new field in each record

what would be the best way to convert that string...I thought php might have a way to do it automatically?

thanks

like image 533
mjr Avatar asked Mar 23 '10 16:03

mjr


People also ask

Which function can be used to convert string to date in MySQL?

MySQL STR_TO_DATE() Function The STR_TO_DATE() function returns a date based on a string and a format.

How do I convert a date to a string in MySQL?

In MySQL, DATE_FORMAT function converts a DATE or DATETIME value to string using the specified format. In Oracle, you can use TO_CHAR function. Note that the DATE_FORMAT and TO_CHAR use different format strings.

How can get date in dd mm yyyy format in MySQL?

The following is the output. The following is the query to format the date to YYYY-MM-DD. mysql> select str_to_date(LoginDate,'%d. %m.

Can we change date format in MySQL?

MySQL uses yyyy-mm-dd format for storing a date value. This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want.


2 Answers

First, convert the string into a timestamp:

$timestamp = strtotime($string); 

Then do a

date("Y-m-d H:i:s", $timestamp); 
like image 52
Pekka Avatar answered Sep 30 '22 13:09

Pekka


If these strings are currently in the db, you can skip php by using mysql's STR_TO_DATE() function.

I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.

UPDATE some_table    SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y') 

You can support other date formats by using other format specifiers.

like image 32
goat Avatar answered Sep 30 '22 13:09

goat