Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a date-time into string in PHP?

Tags:

php

I have a date as follows.

$discount_start_date='03/27/2012 18:47';

$start_date=new DateTime($discount_start_date);
$start_date->format('Y/m/d H:i:s');

How can I convert it to a string in PHP so that it can be stored into MySql? I'm from Java background and very new to PHP.

like image 280
Bhavesh Avatar asked Mar 26 '12 20:03

Bhavesh


People also ask

How to convert DateTime to string in html?

The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.

What does date () do in PHP?

PHP date() Function The PHP date function is used to format a date or time into a human readable format. It can be used to display the date of article was published. record the last updated a data in a database.


2 Answers

Don't use DateTime. The normal php way of doing this sort of thing is to use date() and strtotime();

$discount_start_date = '03/27/2012 18:47';    
$start_date = date('Y-m-d H:i:s', strtotime($discount_start_date));
like image 99
Yada Avatar answered Sep 25 '22 22:09

Yada


You don't actually need to convert it into a string. MySQL has a date, time, datetime, as well as timestamp native data types. You should be able to simply insert the date immediately without casting it to a string so long as you insert it into one of these fields and have it formatted properly.

like image 32
Thomas Wright Avatar answered Sep 23 '22 22:09

Thomas Wright