I have a large list of dates and times, a sample look like this...
11/22/2018 01:16:14 AM
11/23/2018 10:59:39 PM
I assume the dates are in the 'm/d/Y h:i:s A' format, I am looking for the quickest and easiest way in PHP to convert these to an epoch timestamp.
Anyone have an example?
Use strtotime function
echo strtotime("11/22/2018 01:16:14 AM");
You can do it this object oriented way:
$format = 'm/d/Y h:i:s A';
$date = DateTime::createFromFormat($format, '11/22/2018 01:16:14 AM');
echo $date->getTimestamp();
Related
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'])))."'";
I have this line of code I wrote to create a formatted timestamp on emails from my contact us page.
It is working fine, but I'm wondering if it is written poorly and could be reduced into more efficient code? It feels wrong calling date() three times in one line. I'm not a developer by trade.
$timestamp = date('m-d-Y')." ".date('h:i A', strtotime(date('H:i:s')));
which results in: 05-28-2014 03:49 PM
Thoughts?
When you need the current timestamp, you can use,
$timestamp=date("m-d-Y h:i A");
When you need to format the timestamp you fetched from database or other means, you have to use strtotime.
$format_timestamp=date("Y-m-d H:i:s", strtotime($timestamp)); // I just convert your format to YYYY-MM-DD HH:MM:SS format.
Edit:
When you need to subtract x hours from the current time, use
$timestamp=date("m-d-Y h:i A", strtotime("-4 hour"));
Some more examples,
$timestamp=date("m-d-Y h:i A", strtotime("+2 hour")); // Adds 2 hours
$timestamp=date("m-d-Y h:i A", strtotime("+1 day")); // Adds 1 Day
You can simplify making:
$timestamp = date('m-d-Y h:i A');
or
$timestamp = gmdate("M d Y H:i:s");
For more information, see:
PHP Manual
date http://www.php.net/manual/en/function.date.php
gmdate http://www.php.net/manual/en/function.gmdate.php
I have two separate strings for date and time formatted something like: 14/04/2014 and 01:15 PM
I would like to convert these to a datetime formatted as Y-m-d H:i:s
Any idea how I go about this??
$date = DateTime::createFromFormat('d/m/Y h:i A', '14/04/2014'.' '.'01:15 PM');
echo $date->format('Y-m-d H:i:s');
Demo
how would you convert a date stored as
2011-01-18 11:51:41
into
18-01-2011 11:51:41
using PHP?
many thanks in advance!
date('d-m-Y H:i:s', strtotime('2011-01-18 11:51:41'));
More reliable than using strtotime(), assuming you're on PHP 5.3+
$oldtime = date_parse_from_format('Y-m-d h:i:s', '2011-01-18 11:51:41');
$newtime = date('d-m-Y h:i:s', $time);
However, the date format you're converting FROM suggests it's coming from a MySQL datetime field, in which case you could also do:
SELECT DATE_FORMAT(yourfield, '%d-%m-%Y %H:%i:%s')
and save yourself a full roundtrip in PHP.
Convert the old date to UNIX time with strtotime(), then output it in the new format with date()
$olddate = "2011-01-18 11:51:41";
$newdate = date('d-m-Y H:i:s', strtotime($olddate));
echo $newdate;
// 18-01-2011 11:51:41
$your_date = "2011-01-18 11:51:41";
echo date('d-m-Y H:i:s', strtotime($your_date));
demo
This question already has answers here:
Convert from MySQL datetime to another format with PHP
(18 answers)
Closed 2 years ago.
I have a date time in a variable. My format is 08/04/2010 22:15:00. I want to display this like 10.15 PM. How to do this in PHP?
You need to convert it to a UNIX timestamp (using strtotime) and then back into the format you require using the date function.
For example:
$currentDateTime = '08/04/2010 22:15:00';
$newDateTime = date('h:i A', strtotime($currentDateTime));
$dateString = '08/04/2010 22:15:00';
$dateObject = new DateTime($dateString);
echo $dateObject->format('h:i A');
Use strtotime() to make the date a UNIX timestamp.
For output, check out the various options of date().
$timestamp = strtotime("08/04/2010 22:15:00");
date("h.i A", $timestamp);
<?php
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $dateTime->format("d/m/y H:i A");
?>
You can use this to display the date like this
22/06/15 10:46 AM
Like this:
$date = '08/04/2010 22:15:00';
echo date('h:i A', strtotime($date));
Result:
10:15 PM
More Info:
date
strtotime
for flexibility with different formats, use:
$dt = DateTime::createFromFormat('m/d/Y H:i:s', '08/04/2010 22:15:00');
echo $dt->format('g:i A')
Check the php manual for additional format options.
PHP Code:
date_default_timezone_set('Asia/Kolkata');
$currentDateTime=date('m/d/Y H:i:s');
$newDateTime = date('h:i A', strtotime($currentDateTime));
echo $newDateTime;
Output: 05:03 PM
$currentDateTime = $row['date'];
echo $newDateTime = date('l jS \of F Y h:i:s A', strtotime($currentDateTime));
Perfect answer for AM/PM live time solution
<?php echo date('h:i A', time())?>
Just simply right A
{{ date('h:i A', strtotime($varname->created_at))}}
For (PHP >= 5.2.0):
You can use DateTime class. However you might need to change your date format. Didn't try yours.
The following date format will work for sure: YYYY-MM-DD HH-MM-SS
$date = new DateTime("2010-04-08 22:15:00");
echo $date->format("g"). '.' .$date->format("i"). ' ' .$date->format("A");
//output
//10.15 PM
However, in my opinion, using . as a separator for 10.15 is not recommended because your users might be confused either this is a decimal number or time format. The most common way is to use 10:15 PM
It is quite easy. Assuming you have a field(dateposted) with the type "timestamp" in your database table already queried and you want to display it, have it formated and also have the AM/PM, all you need do is shown below.
<?php
echo date("F j, Y h:m:s A" ,strtotime($row_rshearing['dateposted']));
?>
Note: Your OUTPUT should look some what like this depending on the date posted
May 21, 2014 03:05:27 PM