John Davidson

Date not converting properly in PHP

0 comments
Message:


I am trying to convert date from one format to another in PHP but I am having issue doing so. the month and day are properly converted but the year still adopt present year.


20 Apr, 2007 - date I am trying to convert


2021-04-20 - format converting to. Looking at the year, it gives 2021.


What I tried:


Format 1:


$date =  strtotime($_POST['dob']);
$new_date = date('Y-m-d', $date);

format 2:


$idate=date_create($_POST['dob']);
echo date_format($idate,"Y-m-d")

What am I doing wrong?



My Answer:
'Y-m-d');

The issue you are facing is because the date you are trying to convert does not include the year in the original format. When you use strtotime() or date_create() functions in PHP, it will default to the current year if the year is not specified in the input date.

To solve this issue, you can manually append the year to the input date before converting it to the desired format. Here is an example of how you can do this:

php
$input_date = $_POST['dob'];
$input_date .= ', ' . date('Y'); // Append the current year to the input date
$date = strtotime($input_date);
$new_date = date('Y-m-d', $date);
echo $new_date;


By appending the current year to the input date before converting it, you ensure that the year is included in the conversion process and you get the desired output format.

Rate this post

4 of 5 based on 8362 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us