Converting String to Date and Datetime

admin_img Posted By Bajarangi soft , Posted On 03-12-2020

Converting the string to Date and DateTime uses several functions/methods like strtotime(), getDate(). We will see what these functions do. strtotime() – This is basically a function which returns the number of seconds passed since Jan 1, 1970, just like a linux machine timestamp. It returns the number of seconds passed according to the parameter passed to the function.

string to date and datetime

Syntax

 strtotime(parameter);

Parameter

  • Time/Date
  • now(optional)

Return Type Returns the number of seconds passed since Jan 1, 1970.
getDate() This function return the date/time information of the passed parameter(date/time);
Parameter The parameter is optional as it takes the current local time as default parameter.
Return Type It returns the information of the date, day, year, month etc in an array.
Syntax

getDate(parameter);

Code for converting a string to date

<?php



$time_input=strtotime("2020/03/12");
$date_input=getDate($time_input);
print_r($date_input);

?>
 

Code for converting a string to datetime

<?php
$input='03/12/2020 1:33:05';
$date=strtotime($input);
echo date('d/m/y h:i:s',$date);
?>

Note1 We can use “D” in the place of “d” for getting the day in the output
 


<br><br>
<?php 
$input = '05/10/2011 15:00:02'; 
$date = strtotime($input); 
echo date('D/M/Y h:i:s', $date); 
?> 

Note 2 We can use “H” in the place of “h” for getting the time in 24 Hour format in the output

<?php 
$input = '05/10/2011 15:00:02'; 
$date = strtotime($input); 
echo date('D/M/Y H:i:s', $date); 
?> 

Related Post