How to change excel cell date fromat using PHP - php

I want to upload data from csv file and my database only accept yyy-mm-dd date format but sometimes users will enter data as dd/mm/yyy date format so I am tried to do following method using Keboola\Csv
if($header[$c]=='date' && $row[$c]!='')
{
$date_text=['--na','--N/'];
$sexe_text=str_replace($date_text,'N/A',$row[$c]);
if(in_array(array('--na','--N/'),$row))
{
$newRow[$c]=$sexe_text;
}
else
{
$date_array=explode('/', trim($row[$c]));
$date=trim($date_array[0]);
$month=trim($date_array[1]);
$year=trim($date_array[2]);
$date_time=$year.'-'.$month.'-'.$date;
$newRow[$c]=$date_time;
}
}
But it will revert again if that cell format in dd/mm/yyy so Now I want to change that cell format into date YYY-MM-DD how can I do it using PHP

You can direct convert it using date() function.
$exceldate = trim($row[$c]);
$date = date('Y-m-d',strtotime($exceldate));
echo $date;
// 2019-08-09

PHP has already predefined date() to convert dates in any format
Simply replace your code with the code given below
if($header[$c]=='date' && $row[$c]!='')
{
$row[$c] = date('Y-m-d', strtotime($row[$c]));
}
else
{
# if $row[$c] is null, do whatever you want.
}
The PHP date() accepts date in any format, wheather it is separated by forward slashes or hyphens.
To learn more you can see this documentaion
for date() : https://www.php.net/manual/en/function.date.php
and for strtotime() : https://www.php.net/manual/en/function.strtotime.php

Related

How to insert data into table?

I have a large excel sheet which I am inserting data by bulk upload.
My problem is date:
date format is like 09/11/2017. I need to insert this data into table.
Any one can suggest me how to do this by conveting in mysql date format?
Use strtotime() on your first date then date('Y-m-d') to convert it back:
$dateFromExcel = strtotime('09/11/2017');
$newDateToInsert = date('Y-m-d',$dateFromExcel);
echo $newDateToInsert;
// 2017-11-09
if you are using PHP 5.2 or higher
use
$ymd = DateTime::createFromFormat('d/m/Y', '09/11/2017')->format('Y-m-d');
you need to get row first and then use like this.
This is a function to convert date from DD-MM-YYYY to YYYY-MM-DD :
function con2mysql($date) {
$date = explode("-",$date);
if ($date[0]<=9) { $date[0]="0".$date[0]; }
if ($date[1]<=9) { $date[1]="0".$date[1]; }
$date = array($date[2], $date[1], $date[0]);
return $n_date=implode("-", $date);
}
If you are using phpExcel library to uplod exccel file than you can use following line.
It works perfectly for me.
PHPExcel_Style_NumberFormat::toFormattedString($exceldate, 'YYYY-MM-DD');

What's the issue in a code written for comparing the date with today's date?

I'm comparing a date with current date(i.e. today's date). It is expected that the error should come only when the date to be compared is greater than today's date. It should not come for date which is less than or equal to today's date.
I've written following code for it.
$submission_date = $_POST['submission_date']; //The date in mm-dd-yyyy format that is to be tested against today's date. The value in $submission date is 12-25-2014
//This is a future date. Today's date is 12-10-2014 in dd-mm-yyyy format
$current_date = date('m-d-Y');
if (strtotime($submission_date) > strtotime($current_date))
{
echo "Future date not accepted";
}
With the above code I'm not getting errors for future dates, sometimes I'm getting error for previous dates as well.
How to optimize and make this code correct and standard?
If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.
If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().
On the other hand, you could use DateTime class, where you can directly compare objects:
$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');
if ($submission_date > $today_date) {
echo "submission_date is in the future\n";
}
demo
If you need to extract some information from DateTime objects, use format() method on them, which accepts same format as date() function:
echo $today_date->format('m/d/Y'); # 12/11/2014
echo $today_date->format('m-d-Y'); # 12-11-2014
echo $today_date->format('Y-m-d'); # 2014-12-11
echo $today_date->format('Y-Y-Y'); # 2014-2014-2014
demo
I think you need to compare date in 'Y-m-d' or 'd-m-Y' format. I think it is not possible to compare date in 'm-d-Y' format
As we have made changes in your code and we test it works from my side so can you try below.
$submission_date = $_POST['submission_date'];
$current_date = date('d-m-y H:i:s');
if (strtotime($submission_date) > strtotime($current_date))
{
echo "Future date not accepted";
}
Hope this helps.

Why is datetime returning today's date instead of the input date?

<?php
// Convert MMDDYY to YYYY-MM-DD date format to be INSERTed
// into MySQL TABLE.
// If it can't convert the data because of an error, it returns 0000-00-00.
date_default_timezone_set('America/New_York');
function date_convert($date_input) {
try {
$date = new DateTime($date_input);
$date_processed = $date->format('Y-m-d');
} catch(Exception $e) {
echo "Wrong date format $date_input" . "\n";
$date_processed = "0000-00-00";
}
return $date_processed;
}
// MMDDYY (January 1, 2000)
$TRANSACTION_DATE_MMDDYY_raw = "010100";
echo date_convert($TRANSACTION_DATE_MMDDYY_raw) . "\n";
?>
Output:
2013-06-28
I'm expecting it to return 2000-01-01, but it's returning today's date. What am I missing? How can I fix this? Thanks!
You should be using the createFromFormat method. See: http://us2.php.net/manual/en/datetime.createfromformat.php
PHP has no way to know your date is formated like MMDDYY. There are two ways to solve this:
use one of the 'valid formats'. You can eather change your input value, or parse it to a valid format with some string functions or a regex.
use the static createFromFormat method that comes with the DateTime class.
As I presume changing the input is not an option, and parsing the input seems a bit far fetched, using the second method seems the most appropriate here, and would result in changing this:
$date = new DateTime($date_input);
into this:
$date = DateTime::createFromFormat('mdy', $date_input);
The format you specified can't be converted/isnt recognized to be a proper format. Try '2000-01-01'

Generate a data-time format from 2 separated strings

I need to compare date/time that I get from MySQL with a format like: 2013-05-17 15:07:29
From another database, I have data and time separated and in the notation: 130998 081836
I have concatenated the two strings to get only one and I'm trying to convert it to my desired format using:
$dateTimeNmea = $array[9]." ".$array[1]; // 130998 081836
$dateTime = date("Y-m-d H:i:s", $dateTimeNmea); // 1970-01-02 13:23:18
So "it works" on the format but the values are wrong. It could be 1998-09-13 08:18:36
Where is my fault?
It has format siH dmy. Try date_parse_from_format('siH dmy', $string) to get it in array.
130998 081836 is not a format for a date that the date function can understand.
For starters the date() function expects the second param to be a timestamp (read docs for it here)
Then you would need to parse the string into a useable date format via date_parse_from_format and finally into a timestamp
Something like
$string = '130998 081836';
$date = date_parse_from_format('dmY His', $string);
$dateString = date('Y-m-d H:i:s', strtotime(vsprintf('%s-%s-%s %s:%s:%s', $date)));
var_dump($dateString); // var dump just for output/test
The strtotime(vsprintf('%s-%s-%s %s:%s:%s', $date) formats your parsed date into a timestamp which can then be used in date methods second param to get exactly the format you need.

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