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
Related
I've problem with read date value from import value (Excel) to mysql database. i've code as below :
$dataexcel[$i-3]['date_edit'] = date('m/d/Y', strtotime(trim($data['cells'][$i][25])));
i tried use strtotimeto define value from excel, but i've problem to save it into database, if my value in excel with excel date format is 1/1/2018 (it read as 1 Jan 2018, English time format), after i used my code above, it saved become 1970-01-01 it means 1 Jan 1970.
in another example,
i tried another input with date 2/1/2018, it saved into database as 2018-02-02.
from my samples above, in first there missmatch problem with year, then and in the 2nd sample missmatch problem come from date,
so how to declare date to solve my problem, if i want to save date format with simple way?
if there any advice , please, thanks...
From your comment answer, you can modification some code like below :
$date = str_replace("/", ".", $data['cells'][$i][25]);
$dates = date("Y-m-j", strtotime($date));
$dataexcel[$i-3]['date_edit'] = $dates;
$date still pick up from value without used strotime, so date format didn't read correctly...
You can convert the excel date to mysql date like below I did.
//Your input date
$input_date = $sheet->getCellByColumnAndRow(1,$i)->getValue();
$excel_date = $input_date; //here is that excel value 41621 or 41631
//Convert excel date to mysql db date
$unix_date = ($excel_date - 25569) * 86400;
$excel_date = 25569 + ($unix_date / 86400);
$unix_date = ($excel_date - 25569) * 86400;
//echo gmdate("Y-m-d", $unix_date);
//Insert below to sql
$added_date = gmdate("Y-m-d", $unix_date);
A simple function will do this thing
$date = str_replace("/", ".", $data['cells'][$i][25]);// replace the / with .
$date = date("Y-m-d", strtotime($date));
$dataexcel[$i-3]['date_edit'] = $date;
And in the database the default date format is YYYY-MM-DD , so it save correctly to the db
keep it simple. use a defined dateformat when reading the file (the dateformat can be provided as a parameter in case it needs to be adjustable). then, read the date in the following way instead of just using strtotime (taken from php.net's example):
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
relevant example to your code, using the previous $date var:
$dataexcel[$i-3]['date_edit'] = $date->format("y-M-Y");
more info - http://php.net/manual/en/datetime.createfromformat.php
I have a MySQL DB table with a column named "timestamp", a type of timestamp, and attribute of on update CURRENT_TIMESTAMP and a default of CURRENT_TIMESTAMP.
If I add a record to the table, specifying other values, but not the timestamp, then the timestamp is automatically added like 2016-12-28 17:02:26.
In PHP I query the table using the following query
SELECT * FROM history WHERE user_id = 9 ORDER BY timestamp ASC
The result of the query is saved into $rows and I use a foreach to create an array with some of the other values formatted. I am attempting to format the time stamp to UK type 24-hour date time: dd/mm/yy, HH:MM:SS.
I have tried both the date() and strftime() functions as follows:
$formatted_datetime = strftime("%d %m %y %H %M %S", $row["timestamp"]);
$formatted_datetime = date("d/m/y, H:i:s", $row["timestamp"]);
Both of these result in the following notice and the date time being output incorrectly like 01 01 70 00 33 36:
Notice: A non well formed numeric value encountered in /home/ubuntu/workspace/pset7/public/history.php on line 20
I am new to PHP and MySQL and so far none of the other questions or documentation I have seen have successfully addressed performing this conversion.I do not understand why strftime() does not work, nor how to do this properly?
To do this the OO (and most flexible) way use DateTime class and use the static createFromFormat method to instantiate a new DateTime object:
$new_datetime = DateTime::createFromFormat ( "Y-m-d H:i:s", $row["timestamp"] );
Now you can use the $new_datetime object to generate any string representation you'd like by calling the object's format method:
echo $new_datetime->format('d/m/y, H:i:s');
To boot, you since you've a DateTime object you can now also to any manner of transformation (like shifting timezones or adding days), comparison (greater or less than another DateTime), and various time calculations (how many days/months/etc... between this and another DateTime).
DateTime:http://php.net/manual/en/class.datetime.php
Learn it. Love it. Live it.
Normally in MySQL date timestamp save time as YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14) formate you can easily convert them as your wish using date formate but have to convert your input to time first. Following will do the trick
$formatted_datetime = date("d/m/y, H:i:s", strtotime($row["timestamp"]));
Why not make MySQL do the work? And do you really want mm/dd/yy, not dd/mm/yy?
SELECT *, DATE_FORMAT(timestamp, '%m/%d/%y, %T') formatted_date FROM ....
Then you can extract the formatted date as $row['formatted_date'].
See https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’
$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
echo $row['date'] . "
";
}
The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.
Here are some other sample date output formats that may be of practical use:
echo date("F j, Y g:i a", strtotime($row["date"])); // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"])); // 10.05.08
echo date("j, n, Y", strtotime($row["date"])); // 5, 10, 2008
echo date("Ymd", strtotime($row["date"])); // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"])); // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"])); // Sun Oct 5 21:34:02 PST 2008
I would use the Carbon class and its String Formatting
$carbon = Carbon::instance('2016-12-28 17:02:26');
Then you can format it the way you want.
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
Progress :
1. I retireved date from a collection.
Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.
CODE USED :
$cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
// created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
$doc2=$cur->getNext();
$pieces = implode(" ", $doc2);
//converted the array to string with space delimiting
if($pieces!=NULL)
{
$date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
echo date_format ( $date1 , 'Y-m-d G:i:s' );
//This is the format i would like to update in mongodb..
$filter = array('_id'=>new MongoId($doc['_id']));
$update = array('$set'=>array('created_at'=> newMongoDate($date2)));
$col->update($filter,$update);
}
}
QUESTION :
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications
Hmm even though you have explained your background well your actual question:
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
Is a bit confusing.
MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.
So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:
$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));
And you use the original $date1 object to actually save to the database.
Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:
$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));
You can use the $date2 as the date to save into MongoDB formed from the specific format you want.
look at http://php.net/manual/en/class.mongodate.php
your code should create a date using a unix timestamp
$date2 = ('23rd April 2013');
$update = array('$set'=>array(
'created_at'=> new MongoDate(strtotime($date2))
));
http://www.php.net/manual/en/function.strtotime.php
I cannot seem to find any info on this..
I need to convert a string to a date so that it will import properly to an SQL DATE field. When I import 12/25/2012 to the DB, it appears as 0000-00-00.
What's the proper way to do this?
Links and refs appreciated.
MySQL accepts dates in this format YYYY-MM-DD either change your date format 12/25/2012 to 2012-12-25 or modify them to match the correct format.
EDIT
If you want to continue using your own format try this
list($d,$m,$y) = explode("/", "12/25/2012"); //replace 12/25/2012 with your date
$hyphenDate = $y . '-' . $m . '-' . $d;
echo $hyphenDate;
As #Ravi pointed out in his answer, MySQL accepts dates in the format YYYY-MM-DD. Quoted from 11.1.5. Date and Time Types1:
Although MySQL tries to interpret values in several formats, date
parts must always be given in year-month-day order
For this, you can use str_todate()2 function to format it:
str_to_date('12/25/2012', '%m/%d/%Y);
SQL Fiddle Demo
This way, these input strings will be stored in your database as date objects(without any specific date format). Later, if you want to output these dates in a specific format you can use DATE_FORMAT3 to format it. Something like:
SELECT DATE_FORMAT(datefield, '%Y-%m-%d') FROM Test;
--2012-12-25
1, 2, 3: Links and refs, that you asked for.
Use class DateTime. Examples:
$SomeDate = new DateTime();
echo $SomeDate->format( 'Y-m-d H:i:s' ); //Must be MySQL compatible (YYYY-MM-DD)
$ThisDate = new DateTime( date( 'Y-m-d H:i:s' ) );
echo $ThisDate->format( 'Y-m-d H:i:s' ); //Must be MySQL compatible (YYYY-MM-DD)