How to reformat date in PHP? - php

I am pulling the dates of various posts from a database. The dates are in the following format:
2009-08-12
Numeric Year - Numeric Month - Numeric Day
How can I reformat these dates to something more user friendly like:
August 12, 2009
Numeric Month Numeric Date, Numeric Year
Assuming that the date gotten from the mysql database is stored in a variable called:
$date = $row['date_selected'];

Unlike the strtotime based examples, this allows you to ensure the month and day are interpreted in the correct order regardless of locale settings specified on the server.
$date = DateTime::createFromFormat('Y-m-d', '2009-08-12');
$output = $date->format('F j, Y');

date("F d, Y", strtotime($input))

$new_format = date("Your Date String", strtotime($date));
See:
- http://php.net/strtotime
- http://php.net/date
Basically, if strtotime() can read it correctly, you can reformat it anyway you please.
In this case, Year - Month - Day is a properly recognized strtotime() format, this might not be the case for other formats.

You might consider doing your date formatting in MySQL with your select statement:
DATE_FORMAT(date,'%M %e, %Y') as date_selected
http://www.w3schools.com/sql/func_date_format.asp

<?php
echo date('F j, Y', strtotime($date));

You might want to look at the php function strtotime:
http://php.net/manual/en/function.strtotime.php
It'll parse a large number of date representations to a Unix timestamp.
Then use the date function.

Using strtodate or explode to split the date into its different components, you can then use the date function with the appropriate format string:http://php.net/manual/en/function.date.php
$date = "2009-08-12";
list($year,$month,$day) = explode("-",$date);
$formattedDate = date("F d, Y", mktime(0,0,0,$month,$day,$year));
Outputs: "August 12, 2009"

<?php
//Date Formatter
/*
date: date you want to convert
format: its current format ie m-d-Y, m/d/Y, Y-m-d, Y/m/d
delimS: Current delimiter ie - or / or .
delimF: The delimiter you want for the result
NOTE: this will only convert m-d-Y to Y-m-d and back
*/
function dtform($date,$format,$delimS,$delimF){
$dateFinal = '';
if($format == 'm'.$delimS.'d'.$delimS.'Y'){
$dateFinal_exp = explode($delimS,$date);
$dateFinal = $dateFinal_exp[2].$delimF.$dateFinal_exp[0].$delimF.$dateFinal_exp[1];
}else if($format == 'Y'.$delimS.'m'.$delimS.'d'){
$dateFinal_exp = explode($delimS,$date);
$dateFinal = $dateFinal_exp[1].$delimF.$dateFinal_exp[2].$delimF.$dateFinal_exp[0];
}
return $dateFinal;
}
?>

Use it like this:
// February 1, 2005
print date ("F j, Y", mktime (0,0,0,14,1,2004));

Related

How can I set numbers that equals days of month [duplicate]

I have a datetime column in MySQL.
How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?
If you're looking for a way to normalize a date into MySQL format, use the following
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.
(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)
To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)):
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
Refer to the PHP date formatting options to adjust the format.
If you are using PHP 5, you can also try
$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
$valid_date = date( 'm/d/y g:i A', strtotime($date));
Reference: http://php.net/manual/en/function.date.php
Finally the right solution for PHP 5.3 and above:
(added optional Timezone to the Example like mentioned in the comments)
without time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);
echo $date->format('m/d/y h:i a');
with time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
echo $date->format('m/d/y h:i a');
An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.
If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.
Forget all. Just use:
$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.
PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.
$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);
This, and a list of other PHP DateTime constants are available at http://php.net/manual/en/class.datetime.php#datetime.constants.types
This should format a field in an SQL query:
SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
Use the date function:
<?php
echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
Depending on your MySQL datetime configuration. Typically: 2011-12-31 07:55:13 format. This very simple function should do the magic:
function datetime()
{
return date( 'Y-m-d H:i:s', time());
}
echo datetime(); // display example: 2011-12-31 07:55:13
Or a bit more advance to match the question.
function datetime($date_string = false)
{
if (!$date_string)
{
$date_string = time();
}
return date("Y-m-d H:i:s", strtotime($date_string));
}
SELECT
DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,
DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil
FROM demo
If you dont want to change every function in your PHP code, to show the expected date format, change it at the source - your database.
It is important to name the rows with the as operator as in the example above (as dateFrom, as dateUntil). The names you write there are the names, the rows will be called in your result.
The output of this example will be
[Day of the month, numeric (0..31)].[Month name (January..December)].[Year, numeric, four digits]
Example: 5.August.2015
Change the dots with the separator of choice and check the DATE_FORMAT(date,format) function for more date formats.
You can also have your query return the time as a Unix timestamp. That would get rid of the need to call strtotime() and make things a bit less intensive on the PHP side...
select UNIX_TIMESTAMP(timsstamp) as unixtime from the_table where id = 1234;
Then in PHP just use the date() function to format it whichever way you'd like.
<?php
echo date('l jS \of F Y h:i:s A', $row->unixtime);
?>
or
<?php
echo date('F j, Y, g:i a', $row->unixtime);
?>
I like this approach as opposed to using MySQL's DATE_FORMAT function, because it allows you to reuse the same query to grab the data and allows you to alter the formatting in PHP.
It's annoying to have two different queries just to change the way the date looks in the UI.
You can have trouble with dates not returned in Unix Timestamp, so this works for me...
return date("F j, Y g:i a", strtotime(substr($datestring, 0, 15)))
This will work...
echo date('m/d/y H:i (A)',strtotime($data_from_mysql));
Using PHP version 4.4.9 & MySQL 5.0, this worked for me:
$oDate = strtotime($row['PubDate']);
$sDate = date("m/d/y",$oDate);
echo $sDate
PubDate is the column in MySQL.
Direct output e.g. in German format:
echo(date('d.m.Y H:i:s', strtotime($row["date_added"])));
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";

date conversion in CodeIgniter / PHP does not gives output

I have date in this type of format: April 1st 2017 and I want to convert it into this type of format: 2017/04/01 in my CodeIgniter code using php. I have used below posted piece of code but it is not working. Please solve the issue.
Code:
$date = DateTime::createFromFormat('m/d/Y', "April 1st 2017");
echo "Date = ".$date->format('Y-m-d');
You can use strtotime() and date() php functions as
$newDate = date("m/d/Y", strtotime("April 1st 2017"));
Or in CodeIgniter
$date = DateTime::createFromFormat('j F Y - H:i', 'April 1st 2017');
echo $date->format('m/d/Y H:i:s');
Your format can be used in the constructor of DateTime. See accepted formats.
$date = new DateTime("April 1st 2017");
echo "Date = ".$date->format('Y-m-d');
Outputs:
Date = 2017-04-01
If you want to use DateTime::createFromFormat(), you have to use the proper format
"F jS Y"
The format you specified for your date is incorrect.
It would convert '04/01/2017' but it does not suit
April 1st 2017.
Try instead: createFromFormat('F dS Y')
Explanation:
F - full textual representation of a month, such as January.
d - day
S - English ordinal suffix for the day of the month
Y - 4-digit representation of year
you can try this also
<?php
$date='22 march 2018';
echo date('m/d/Y', strtotime($date));
?>

Today's date format - Day (Shorthand) Date Number Month (Shorthand) - PHP

I have a feed which gives feed in the following format: "Fri 14 Oct"
I want to see if today's date matches the date from the feed. My problem is the format of today's date/
$today = date("d m");
This outputs 17 10.
What is the best way to format $today so that it outputs Day (shorthand) space date (number) Month (shorthand) ?
how about:
$today = date("D j M");
As explained in date() reference manual.
Anyway you should be aware of timezone issues unless you are 100% sure that your server is in the same timezone of the feed you are comparing.
I would follow a different approach though, you can parse the feed's date using DateTime::createFromFormat() which also understand timezones, and then compare it with today's date.
$today = date("D d M");
PHP Date Documentation
<?php
// Prints the day
echo date("l") . "<br>";
// Prints the day, date, month, year, time, AM or PM
echo date("l jS \of F Y h:i:s A");
?>
For more details, please visit http://www.w3schools.com/php/func_date_date.asp

PHP date year format

I am having problems with dates in php- sometimes the date gets to us in d/m/y and other times its d/m/Y. I want to convert all dates to d/m/Y.
Working with my current dataset, how would I get 24/06/2015 from 24/06/15 using php?
So far I have tried :
$original_date = '24/06/15';
$new_date = date('d/m/Y', strtotime($original_date));
This brings back 01/01/1970
This is probably the most robust method:
$string = '24/06/15';
$date = DateTime::createFromFormat('d/m/y', $string) ?: DateTime::createFromFormat('d/m/Y', $string);
echo $date->format('d/m/Y');
createFromFormat returns false if you try to parse 24/06/2014 using the d/m/y format, so in that case you just retry with d/m/Y. You then get a DateTime object which you can format and output any way you like.
use the lowercase 'y'. See the PHP date manual.
$new_date = date('d/m/y', strtotime($original_date));
y = A two digit representation of a year
The problem is that the strtotime doesn't recognise the UK date format, so convert the format first then format the date.
Try this:
$original_date = "24/06/15";
list($date,$month,$year) = sscanf($original_date, "%d/%d/%d");
$date_convert = $year."-".$month."-".$date;
$new_date = date("d/m/Y", strtotime($date_convert));
echo $new_date;
Its wrong format of date you are using for strtotime.
Have a look at Date Formats
The correct code should have
$original_date = '15/06/24'; // Notice : its mm/dd/yy here
$new_date = date('d/m/Y', strtotime($original_date));

Change date format from dashes to nicer fomrat

I have dates that are being stored in the database like this:
08-11-2013
(That's Day, Month year BTW) Is there a way (without changing the database entries) to output this on a page like this instead...
8th November, 2013
Cheers.
FYI, this would be a lot easier if you stored your dates in MySQL standard Date format.
Use MySQL's DATE_FORMAT() with STR_TO_DATE()
SELECT DATE_FORMAT(STR_TO_DATE(datecol, "%d-%m-%Y"), "%D %M, %Y")
But if you have to do it with PHP you can use DateTime::createFromFormat()
$dt = DateTime::createFromFormat('08-11-2013', "d-m-Y");
echo $dt->format('jS M, Y');
While other's answers are valid, this will output the date in the exact format you asked for in your question.
$date = '08-11-2013';
$prettydate = date('jS F, Y', strtotime($date));
echo $prettydate;
In PHP try
<?php
$olddate = '2012-07-18';
$date = new DateTime($olddate);
echo $date->format('jS F, Y');
?>
Also try to read Convert date format yyyy-mm-dd => dd-mm-yyyy
Enjoy coding! :D

Categories