PHP Excel Date Issue - php

I am not new to PHP, but new to PHPExcel, using it for the first time.
So I preferred to just dump data from excel sheet into an array
$importData = $objImport->getActiveSheet()->toArray(null,true,true,true);
But the problem with this is that date values are returned in format mm-dd-yy, so,
year 2013 and 1913 are both returned as '13' in yy form.
I would like to receive it in yyyy form.

try this
$fDate = $importData[1][C];
$fDate='10-29-14';
$fDate= explode('-', $fDate);
$fDate=$fDate[1].'-'.$fDate[0].'-'.str_pad('14', 4, '20',STR_PAD_LEFT);
echo $fDate;// 29-10-2014

Related

Multidimensional array with different keys to format data

I have multidimensional dynamic array with following structure
$xData["invoice"]["no"]["data"] = "DY-13123";
$xData["invoice"]["date"]["data"] = "01-08-2018";
$xData["invoice"]["total_due"]["data"] = 56890.23;
$xData["invoice"]["due_date"]["data"] = "01-12-2018";
$xData["from"]["name"]["first"]["data"] = "Company Name, Inc";
$xData["from"]["address1"]["data"] = "12345 Sunny Road";
$xData["from"]["address2"]["data"] = "Sunnyville, CA 12345";
I want to allow users to format the data of array by specifying format. For example $xData["invoice"]["date"]["data"]= "01-08-2018"
for this, user can specify the format as date type and formatting as "YYYY-mm-dd". I am storing this format information in another array.
$xFormat["invoice"]["date"] = array("date","YYYY-mm-dd");
$xFormat["invoice"]["total_due"] = array("currency","$");
Now, I need to get the value of $xData and apply the formatting. I have tried getting all keys and applying the format but no success. Please let me know how
to do this.
Thanks in advance
What you need to do is, first take the string in date field and convert it to time, then format it with the format in $xFormat
$time = strtotime($xData["invoice"]["date"]["data"]); //converting the date in string to seconds since January 1 1970 00:00:00 UTC
if ($time === false) { //if the date couldn't be converted to seconds
echo "date is wrong";
} else {
echo date($xFormat["invoice"]["date"]["date"],$time); //yes, double date fields is correct
}
The function strtotime converts a string representation of a time to seconds, which in turn can be used in date. Since you have set $xFormat["invoice"]["date"] as array("date","YYYY-mm-dd"), I had to use $xFormat["invoice"]["date"]["date"]

Reading date from uploaded Excel file

I am uploading an Excel file through PHP Excel. The column C has dates in format mm/dd/yyy.
When I echo the date for example '10/3/2016' it reads it as 42646. The format set for the column is short Date.
How can I read it as the normal date instead of 42646.
here is the model
function fi_upload($file_name){
$file = './uploads/'.$file_name;
$this->load->library('excel');
$objPHPExcel = PHPExcel_IOFactory::load($file);
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
$data['header'] = $header;
$data['values'] = $arr_data;
$datecell = $objPHPExcel->getActiveSheet()->getCell('P2');
if(PHPExcel_Shared_Date::isDateTime($datecell)) {
$InvDate = date($format="Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($datecell));
}
echo $InvDate;
exit();
foreach ($arr_data as $q){
echo $q['C']; // column of date, date is echoed as 42646
exit(); //here i exit to display the date
}
I have to later insert it in the database as well in the yyyy/mm/dd format (which I can do if it is read properly)
Thanks.
UPDATE:
So apparently it was an Excel file issue, not php. Converting the cell values through TEXT() was the solution as suggested by #Hallur.
UPDATE 2.0:
I am trying to do it via PHPEXCEL method but I get the following two issues.
: Object of class PHPExcel_Cell could not be converted to int
Echoes date as 2036-02-07 where as the date in cell is 10/4/2016
42646 is an MS Excel serialized timestamp value, the number of days since 1st January 1900 (or 1st January 1904, depending on whether the spreadsheet is using the Windows or Mac calendar)
PHPExcel provides a variety of functions to convert values between MS Excel serialized timestamps and Unix timestamps or PHP DateTime objects (or vice versa), all of which can be found in the PHPExcel_Shared_Date class, e.g.
ExcelToPHP() to convert an MS Excel serialized timestamp to a unix timestamp
ExcelToPHPObject() to convert an MS Excel serialized timestamp to a PHP DateTime object
Alternatively, using the getFormattedValue() method instead of getValue() will return a formatted date/time string value instead of the serialized tiemstamp
$field1= $objWorksheet->getCellByColumnAndRow(0,$i)->getFormattedValue(); //Excel Column 3
$date = PHPExcel_Shared_Date::ExcelToPHP($field1); //unix
echo $field1= gmdate("Y-m-d", $date); //date
Already wrote answer this link
The answer to this question is here:
Excel weird behaviour with dates => text
The number 42646, is the amount of days since january 1st year 1900.
To convert the excel base date to unix time ( time() ), you must calculate the difference between unix start to excel base time start. (unix start: d-m-Y H:i:s -> 01-01-1970 01:00:00) (excel start: d-m-Y -> 1-1-1900)
First to get the difference, which is approximately 70 years and 1 hour (+ 1 extra day because excel date 1-1-1900 = 1, not 0.)
70 years, 1 day, 1 hour = 70 years + 25 hours. (to make up for leap years, we have to say 365.25 instead of 365 days in a year)
(70*365.25*24*60*60)+(25*60*60)
Now, we need to convert the excel date value to seconds as well: 42646*24*60*60 (~ 116 years)
We need to subtract them from each other to get the unix time, and since the excel date is higher than the 70 years, we put that first.
to echo out the day:
echo date("d-m-Y", (42646*24*60*60) - ((70*365.25*24*60*60)+(25*60*60)));
EDIT: I just realized that extra hour is because of my timezone.. CET, not UTC.

Error Import Excel Date PHP

I have a problem trying to upload an excel to my database through PHP.
The format I have in the excel is dd/mm/yyyy and my sql needs yyyy/mm/dd
$_DATOS_EXCEL[$i]['ship_day']= $objPHPExcel->getActiveSheet()- >getCell($headings['Ship Date'].$i)->getFormattedValue();
I tried
getFormattedValue('YYYY/MM/DD');
but doesnt work
I really appreciate if you can help me out with this.
If your cell value really is an Excel serialized date/time value, and you know which cells contain these dates, then you can convert it directly to a PHP DateTime object
$dto = PHPExcel_Shared_Date::ExcelToPHPObject(
$objPHPExcel->getActiveSheet()
->getCell($headings['Ship Date'].$i)
->getValue()
);
$_DATOS_EXCEL[$i]['ship_day'] = $dto->format('Y/m/d');
or to a Unix Timestamp
$unixTimestamp = PHPExcel_Shared_Date::ExcelToPHP(
$objPHPExcel->getActiveSheet()
->getCell($headings['Ship Date'].$i)
->getValue()
);
$_DATOS_EXCEL[$i]['ship_day'] = date('Y/m/d', $unixTimestamp);
Add three line after
"$_DATOS_EXCEL[$i]['ship_day']= $objPHPExcel->getActiveSheet()- >getCell($headings['Ship Date'].$i)->getFormattedValue();"
this line......
$rearrange=$_DATOS_EXCEL[$i]['ship_day'];
$explode = explode("/",$rearrange);
$_DATOS_EXCEL[$i]['ship_day']= $explode[2]."/".$explode[1]."/".$explode[0];

PHPExcel Date Format

I am getting an output from MS SQL server in the '2012-08-09 00:00:00' (without quotes) format.
However, when I write it to excel file I'm unable to write it in date format to have dd mmm yyyy formatting on excel.
As a result i tried to write in format =date(2012,08,09) as a formula to the respective cells.
But I don't want to output it as a formula but rather the value '09 Aug 2012' with the data type integrity intact. How do I do this? Or is there a simpler method?
I read through the documentation but it was not clear to me, thought I would ask for clarification.
Regards.
Sorry for not being detailed enough.
I am using the PHPExcel library.
From my sql array, i use the following:
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],5,2);
$t_day = substr($xls_column_datas["colname"],8,2);
$t_format = $t_year . "," . $t_month . "," . $t_day ;
$t_format = '=date('.$t_format.')';
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($data_column_num, $data_row_num, $t_format );
$objPHPExcel->getActiveSheet()->getStyleByColumnAndRow($data_column_num, $data_row_num)->getNumberFormat()->setFormatCode('[$-C09]d mmm yyyy;#');
in my excel output, it shows column A2 for e.g. =DATE(2012,8,9)
rather than showing up as a formula I want excel to recognize '2012-08-09 00:00:00' is a date time and format it to dd mmm yyyy.
Is this getting clear? Sorry.
Is your problem in getting the date from MS SQL as a date/time, or setting the Excel date?
There is a whole section of the PHPExcel documentation that explains the use of the PHPExcel_Shared_Date::PHPToExcel($PHPDate) and PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) helper methods for converting PHP dates to an Excel datetime stamp value that you set as the cell value, and then you apply a number format mask of one of the date masks such as PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 to that cell
Instead of
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],5,2);
$t_day = substr($xls_column_datas["colname"],8,2);
$t_format = '=date('.$t_format.')';
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($data_column_num, $data_row_num, $t_format );
$objPHPExcel->getActiveSheet()->getStyleByColumnAndRow($data_column_num, $data_row_num)->getNumberFormat()->setFormatCode('[$-C09]d mmm yyyy;#');
try setting
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],4,2); // Fixed problems with offsets
$t_day = substr($xls_column_datas["colname"],6,2);
$t_date = PHPExcel_Shared_Date::FormattedPHPToExcel($t_year, $t_month, $t_day);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(
$data_column_num, $data_row_num, $t_date
);
$objPHPExcel->getActiveSheet()
->getStyleByColumnAndRow($data_column_num, $data_row_num)
->getNumberFormat()->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14
);
$date = PHPExcel_Style_NumberFormat::toFormattedString($data, "M/D/YYYY");
Though it is unclear what are asking, If you are looking for a date conversion
// convert old date string to YYYYmmdd format
$date = date('d M Y', strtotime($old_date));
this will output date in 09 Aug 2012 format
Why not let the server to the formatting for you? Use this query to format the date
SELECT convert(varchar(15), getdate(), 106)
This will result 11 Sep 2012
SQL SERVER: Date Format

Mismatch when converting Excel date numbers to Unix Timestamp using PHP

Hi~ I am using PHPExcel 1.7.7 to read XLSX files and present the results in web pages.
I'm trying to get the value of a cell that stores a date & time string and process it in PHP using the following code.
<?php
date_default_timezone_set('Australia/Canberra');
$value = $objPHPExcel->getActiveSheet()->getCell('A1')->getValue();
define('MIN_DATES_DIFF', 25569);
define('SEC_IN_DAY', 86400);
function excel2Timestamp($excelDate)
{
if($excelDate <= MIN_DATES_DIFF)
{
return 0;
}
return ($excelDate - MIN_DATES_DIFF) * SEC_IN_DAY;
}
echo $result = date('H:i:s d/m/Y', excel2Timestamp($value));
?>
while the original value in the cell is "00:00:00 01/07/2012", instead of giving me the correct results, the output from the above PHP code shows "10:00:00 01/07/2012".
It seems that it is caused by the time zone differences, but I have already defined the time zone at the beginning of the code. No idea what is wrong with it.
Can anyone please help me with it? Thanks in advance.
Forget your function to convert to timestamp (I was doing the same too)... PHPExcel does the convertion automatically, so try doing this:
//get the excel date value (if it's stored in the A1 cell)
$excelDate = $objPHPExcel->getActiveSheet()->getCell('A1')->getValue();
//converts from excel format to a datetime object
$date = PHPExcel_Shared_Date::ExcelToPHPObject($excelDate);
//format the date as you want.
$formatedDate = $date->format('m/d/Y');
It should work.

Categories