Format date function - Customizing output - php

I am new on PHP and I am trying to retrieve date from my database and format it from this: yyyy-mm-dd hh:mm:ss to this format: dd-mm-yyyy hh:mm:ss. My first thought was to convert the format before store in the server, but I have read that it is a bad practice, so I am trying to do it when outputting the data.
The point is, it is not working, when I use Format function it changes the format, but in a wrong way.
In this example I am using 'MM/dd/yyyy' format string, but I have already tryied with different formats and the output is always the same.
The table column is in datetime format, but I have experimented with text and varchar formats, in the first case the output is the same as the one from datetime format and in the second case I just receive the first four numbers.
One more thing, I am using PDO.
This is my query:
public function funcaoTesteGetValues() {
$query = "SELECT teste_data,FORMAT(teste_data,'MM/dd/yyyy') AS 'nova_data' FROM teste";
$stmt = $this->conexao->prepare($query);
$stmt->execute();
return $stmt->fetchAll(\PDO::FETCH_OBJ);
}
Here goes the output:
[teste_data] => 2015-12-04 04:04:00 => database format (datetime)
[nova_data] => 20,151,204,040,400 => output formatted
What I need:
04-12-2015 04:04:00

FORMAT() is for numbers rounded to a certain number of decimal places. You want DATE_FORMAT() with the correct format identifiers
DATE_FORMAT(teste_data,'%m/%d/%Y') AS 'nova_data'
Note This is only if your database server is MySQL.

Related

Date in varchar format not working with query with date

I have a field name 'orderdate' (type Date format yyyy-mm-dd).when i am executing the following query it doesnot show any result.What may be the problem, is the date format used in my query creating problem.plz soggest any solution .I can not change the format of orderdate in table. my query is
SELECT
stationerytype,
txntype,
stationeryqtyrecd,
stationeryqtyissued,
stationeryissueddate,
orderdate,
SUM(stationeryqtyrecd) as ttlreceived
FROM tblstationerystock
WHERE
(
stationerytype ='A4 White Ream' AND
txntype ='received'
) AND orderdate<07/09/21
Simply enclose your date in a Single ' quote or Double " qoute like orderdate<'2021-07-09'; and kindly try using the default MySQL Date Format yyyy-MM-dd.
SELECT stationerytype,
txntype,
stationeryqtyrecd,
stationeryqtyissued,
stationeryissueddate,
orderdate,SUM(stationeryqtyrecd) as ttlreceived
FROM tblstationerystock
WHERE (stationerytype ='A4 White Ream' AND txntype ='received') AND orderdate<'2021-07-09';
MySQL DATE is one of the five temporal data types used for managing date values. MySQL uses yyyy-mm-dd format for storing a date value. This format is fixed and it is not possible to change it.
For example, you may prefer to use mm-dd-yyyy format but you can’t. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want.
Check this.

Converting date to country requirements

I have a calendar in html form and I want to insert this date into MySQL. The default MySQL date is 0000-00-00. But in my country the format is DD/MM/YYYY. So what to do to fix it. Thank you. I am using PHP.
You must use one format in your HTML page, and another format in your database.
So, if you want to store a date like this '12/05/2008' into mySql, you must transform it like this:
$date = '12/05/2008';
$dateToStore = date('Y-m-d', strtotime(str_replace('/','-',$date)));
And if you wonder why, you need to replace the '/' with '-' to make php know that the first part of the data string is the day, and then the month (as I think is your case).
MySQL the date format is always YYYY-MM-DD. To convert it to another format, you need to manually convert the retrieved date to the desired format like
$displayDate=date("d/M/Y", strtotime($mysqldate));
Method 1
You cant insert into DD/MM/YYYY format. Instead while rendering it in view file you can change into desired format.
<?php
$date = $result['db_date']; // I ASSUMED YOUR DB FIELD IS db_date
$desiredFormat = date('d/m/Y', strtotime($date)); // CONVERTING INTO YOUR FORMAT
echo '<pre>'; print_r($desiredFormat); // DISPLAYING IT
?>
Method 2
You can retrieve from database in your desired format using below
SELECT *, DATE_FORMAT(YOUR_DATE_FIELD, "%m/%d/%Y") AS date FROM YOUR_TABLE;
Use MySQL STR_TO_DATE
Try this mysql query :-
INSERT INTO `table`(`date`) VALUES (STR_TO_DATE('10/10/2015', '%d/%m/%Y'))

How to read a date with ExcelBundle [Symfony Bundle]

I'm having an issue while I'm trying to read cell value with $cell->getCalculatedValue() of a DateTime cell.
The excel file value is 28/2/15 (in format d/m/y) but I get 42063.
Is this a problem with the format? If it is, how I can solve it?
MS Excel date/time values are a float, not a formatted string, or any other special datatype; and it's only the number formatting mask that differentiates them from any other float
getCalculatedValue() will handle any formulae, but won't apply any formatting, so you'll simply get the float value back
however
getFormattedValue() will calculate any formula for the cell, but also apply any number formatting mask, so a "date" will be returned as a formatted string dependent on the number format mask for that cell
EDIT
The formatted string returned is dependent on the number format mask used.... unfortunately some MS Excel date format masks are locale aware, but PHPExcel is not, so if the cell uses one of these masks then the result may not be formatted as you'd want.
You can apply manual formatting for a cell value, using a format mask of your choice:
$result = PHPExcel_Style_NumberFormat::toFormattedString(
$cell->getCalculatedValue(),
PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY
);
or
$result = PHPExcel_Style_NumberFormat::toFormattedString(
$cell->getCalculatedValue(),
'dd/mm/yy'
);
Alternatively, you can convert that MS Excel serialized timestamp to a unix timestamp using
$result = PHPExcel_Shared_Date::ExcelToPHP(
$cell->getCalculatedValue()
);
or to a PHP DateTime object
$result = PHPExcel_Shared_Date::ExcelToPHPObject(
$cell->getCalculatedValue()
);
and then use normal PHP date() or DateTime::format() masking to format it however you want
EDIT #2
To identify if a cell contains a date:
if (PHPExcel_Shared_Date::isDateTime($cell)) {
echo 'Cell ', $cell->getCoordinate(), ' contains a date value';
}

Formatting the time hh:mm:ss.0000000 to hh:mm not working

I am using MsSQL in PHP. I am storing the time in database table row with datetime as datatype.The time is stored like this :08:30:00.0000000.I need the time to be displayed in 08:30.I have used
date('h:i', $time_value); // $time_value stores the time value
This formats the date and gives the result in 4:00. Any formatting is required to display the correct time stored in database?
The PHP date function does not expect a Mysql datetime as second parameter but you do so:
date('h:i', $time_value);
^
|
second parameter
This is the reason why it does not work. You're using the wrong value, convert the database value into a timestamp first because the date function needs a timestamp. As you migh imagine, this has been done before, here is just a selection of related Q&A material:
MySQL convert datetime to unixtime?
MySQL convert datetime to Unix timestamp
Alternatively just use a string function like substr to obtain the string you're looking for:
$time_value = '08:30:00.0000000';
echo substr($time_value, 0, 5); # 08:30
Demo: https://eval.in/146148
You can do the conversion / formatting with the SQL statement already, a related example is given in:
How to display time in HH:MM format?
You can also use:
date('h:i', strtotime('08:30:00.0000000'));
In your case:
date('h:i', strtotime($time_value));

MYSQL mixing up dates

I am trying to insert a date in my Database which I get from a php input.
The code I am using to insert the value looks like this
$length = strrpos($fristdatum, " ");
$newDate = explode(".", substr($fristdatum, $length));
$fristdatum = $newDate[2] . "-" . $newDate[1] . "-" . $newDate[0];
Lets say I enter 14.12.2012 as the date if I echo $fristdatum I get 2012-12-14 but as soon as I insert it in my MySQL DB it turn to 2014.12.20 any ideas?
The Column Type is date. The insert is somewhat like this
mysql_query("INSERT INTO sch_anschreiben (date)values('$fristdatum'))
there are more values but I guess that doesn't matter
Thanks in Advance!
Well thanks for the help guys i figured it out i used $fristdatum in a array for str_replace ,after i formated it, like this
$patern = array("[Date]")
$words=array($fristdatum)
$content = str_replace($patern, $words, $content);
and after that inserted it in the DB now I changed it so it would format after the str_replace and it seems to work just fine.
also would appreciate if someone could explain me why^^.
Instead of explode and hard coded conversion, prefere using DateTime::createFromFormat if you have PHP 5.3 or later.
$date = DateTime::createFromFormat('d. m. Y',$fristdatum);
echo $date->format('Y-m-d');//echoes 2012-12-14
Now that you correct your script to register your dates the right way, you should ensure your database is good.
You can use this request I think :
UPDATE yourtable SET yourdate=CONCAT(MONTH(yourdate),'-',DAY(yourdate),'-',YEAR(yourdate)) WHERE MONTH(yourdate) > 12
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
So if you want to store it like 14-12-2012 then use its datatype as varchar.
Convert it into Y-M-D format. You should directly put 2012-12-14 onto your database.

Categories