Circular References in PHPExcel - infinite loop or wrong result - phpexcel

I am using PHPExcel 1.8.0
I have read the posts regarding circular references, such as this one, but I am still running into issues.
If a spreadsheet contains one circular ref. formula, PHPExcel's calculations do not match MS Excel.
If a spreadsheet contains more than one circular ref, then PHPExcel goes into an infinite loop.
Here are the details of what I've done so far.
Assume a spreadsheet where A1 = B1 and B1 = A1+1, and Excel is set to 100 iterations. Here is my code:
// create reader
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
// load workbook
$objPHPExcel = $objReader->load($this->_path);
// set iterative calculations max count
PHPExcel_Calculation::getInstance($objPHPExcel)->cyclicFormulaCount = 100;
// calculate
$objWorksheet = $objPHPExcel->getSheetByName('Testing');
$data = $objWorksheet->rangeToArray('A1:B1');
echo '<pre>';
print_r ($data);
echo '</pre>';
// release resources
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
MSExcel results in A1 = 99, B1 = 100. My code produces this:
Array
(
[0] => Array
(
[0] => #VALUE!
[1] => #VALUE!
)
)
Further to that, if I add A2 = B2 and B2 = A2+1, and attempt to calculate (A1:B2), it goes into an infinite loop and eventually crashes:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes) in C:\xampp\htdocs\cgc\bulldog\application\third_party\PHPExcel\Calculation.php on line 2837
Here is what I've done so far. In _calculateFormulaValue in Calculation.php:
Line 2383: $cellValue = ''; - this is the cause of the #Value! error. I changed that to $cellValue = 0;
Line 2400:
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
This is the cause of the infinite loop. $this->_cyclicFormulaCell does not get re-set to '' after the formula in row 1 is done, so this condition does not work for the formula in row 2.
I fixed this as follows, starting from Line 2389:
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsTitle.'!'.$cellID))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
} elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) &&
($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
} elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) {
++$this->_cyclicFormulaCount;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
}
After these fixes, if I run $data = $objWorksheet->rangeToArray('A1:B2');, I get the following result:
Array
(
[0] => Array
(
[0] => 100 // should be 99
[1] => 100
)
[1] => Array
(
[0] => 100 // should be 99
[1] => 100
)
)
As you can see, the results from PHPExcel are not consistent with MS Excel. Why is this happening and how can I get around this?

Ok, I managed to debug this. My spreadsheet was very complicated, lots of circular refs. The most challenging is a scenario where A depends on B, B depends on both A and C, and C depends on B.
I also added a maxChange parameter, so the thing works like Excel. Otherwise it takes too long on my spreadsheet.
Anyway, here is a usage example:
$objPHPExcel = PHPExcel_IOFactory::load($path);
$objCalc = PHPExcel_Calculation::getInstance($objPHPExcel);
$objCalc->cyclicFormulaCount = 100;
$objCalc->maxChange = 0.001;
The two files that were modified are: Calculation.php and CalcEngine/CyclicReferenceStack.php
Here is the code (sorry Mark, I can't afford more time to submit it to git properly).
Calculation.php
add these to class properties:
private $_precedentsStack = array();
public $maxChange = 0;
replace _calculateFormulaValue() function with this:
public function _calculateFormulaValue($formula, $cellID=null, PHPExcel_Cell $pCell = null) {
$this->_debugLog->writeDebugLog("BREAKPOINT: _calculateFormulaValue for $cellID");
// Basic validation that this is indeed a formula
// We simply return the cell value if not
$formula = trim($formula);
if ($formula{0} != '=') return self::_wrapResult($formula);
$formula = ltrim(substr($formula,1));
if (!isset($formula{0})) return self::_wrapResult($formula);
// initialize values
$pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
$wsTitle = ($pCellParent !== NULL) ? $pCellParent->getTitle() : "\x00Wrk";
$key = $wsTitle.'!'.$cellID;
$data = array(
'i' => 0, // incremented when the entire stack has been calculated
'j' => 0, // flags the formula as having been calculated; can only be 0 or 1
'cellValue' => $pCell->getOldCalculatedValue(), // default value to start with
'precedents' => array(),
'holdValue' => FALSE // set to TRUE when change in value is less then maxChange
);
// add this as precedent
$this->_precedentsStack[] = $key;
// if already been calculated, return cached value
if (($cellID !== NULL) && ( $this->getValueFromCache($wsTitle, $cellID, $cellValue))) {
return $cellValue;
}
$this->_cyclicReferenceStack->getValueByKey($key, $data);
extract($data);
$this->_debugLog->writeDebugLog("iteration # $i");
// if already calculated in this iteration, return the temp cached value
if ($i >= $this->cyclicFormulaCount || $j == 1) {
return $cellValue;
}
// on stack, but has not yet been calculated => return default value
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($key))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
}
return $cellValue;
}
// calculate value recursively
$this->_cyclicReferenceStack->push($key);
$cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
$this->_cyclicReferenceStack->pop();
// everything in precedent stack after the current cell is a precedent
// and every precedent's precedent is a precedent (aka a mouthfull)
while ( $this->_precedentsStack[ count($this->_precedentsStack) - 1 ] != $key ){
$data['precedents'][] = array_pop($this->_precedentsStack);
}
$data['precedents'] = array_unique($data['precedents']);
// check for max change
$oldValue = $this->_extractResult($data['cellValue']);
$newValue = $this->_extractResult($cellValue);
$data['cellValue'] = $cellValue;
$data['holdValue'] = (abs($oldValue - $newValue) < $this->maxChange);
// flag as calculated and save to temp storage
$data['j'] = 1;
$this->_cyclicReferenceStack->setValueByKey($key, $data);
// if this cell is a precedent, trigger a re-calculate
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
if ( $tempData['holdValue'] == TRUE && ( in_array($key, $tempData['precedents'])) ) {
$tempData['holdValue'] = FALSE;
}
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
// at the end of the stack, increment the counter and flag formulas for re-calculation
if (count($this->_cyclicReferenceStack->showStack()) == 0) {
$i++;
$this->_precedentsStack = array();
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
$tempData['i'] = $i;
if ( ! $tempData['holdValue'] ) $tempData['j'] = 0;
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
$this->_debugLog->writeDebugLog("iteration # $i-1 finished");
}
if ($i < $this->cyclicFormulaCount) {
$cellValue = $this->_calculateFormulaValue($pCell->getValue(), $cellID, $pCell);
} elseif ($cellID !== NULL) {
// all done: move value from temp storage to cache
$this->saveValueToCache($wsTitle, $cellID, $cellValue);
$this->_cyclicReferenceStack->removeValueByKey($key);
}
// Return the calculated value
return $cellValue;
} // function _calculateFormulaValue()
add this helper function:
private function _extractResult($result) {
if (is_array($result)) {
while (is_array($result)) {
$result = array_pop($result);
}
}
return $result;
}
CyclicReferenceStack.php
add a property:
private $_values = array();
add a bunch of functions:
public function setValueByKey($key, $value) {
$this->_values[$key] = $value;
}
public function getValueByKey($key, &$value) {
if (isset($this->_values[$key])) {
$value = $this->_values[$key];
return true;
}
return false;
}
public function removeValueByKey($key) {
if (isset($this->_values[$key])) {
unset($this->_values[$key]);
}
}
public function showValues() {
return $this->_values;
}

Related

Pagination on DevExtreme dxDataGrid with Skip / Take loadOptions

We have a table with a large amount of data and I do not want to load it at once for my dxDataGrid.
I want to implement paging with Skip / Take which is supplied from the dxDataGrid's DataSourceLoadOptions.
This is my controller:
[HttpGet]
public async Task<Object> GetSalesOrdersWithTotals(DataSourceLoadOptions loadOptions)
{
try
{
var results = await SalesOrderService.GetSalesOrdersWithTotals(loadOptions.Skip, loadOptions.Take, 40);
loadOptions.Skip = 0;
loadOptions.Take = 0;
return DataSourceLoader.Load(results, loadOptions);
}
catch (Exception ex)
{
return Json(new { code = "422", success = false, message = "Unable to fetch sales orders with totals - " + ex.ToString() });
}
}
This is the service that returns the data:
public async Task<IEnumerable<SalesOrderWithTotals>> GetSalesOrdersWithTotals(int skip, int take, int defaultPageSize)
{
if (take == 0)
{
//Fix for passing a 0 take
take = defaultPageSize;
}
var salesOrderWithTotals =
from o in _context.SalesOrder
select new SalesOrderWithTotals
{
SalesOrderId = o.SalesOrderId,
Net = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum(),
Tax = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage /100),
Gross = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() + _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage / 100),
Name = o.Customer.Name,
CustomerOrderNumber = o.CustomerOrderNumber,
Contact = o.Contact,
OrderDate = o.OrderDate
};
return await salesOrderWithTotals.Skip(skip).Take(take).ToListAsync();
}
Looking at SQL profiler, this takes the first 40 records but of course the dxDataGrid is not aware of the total count of records so pagination is not available.
What would be the best method to achieve what I want in this case?
Many thanks
You must do an extra query to get the count of your SalesOrder and keep it in for example salesOrderCount. Then keep the Load method return data as bellow.
LoadResult result = DataSourceLoader.Load(results, loadOptions);
LoadResult has a parameter called totalCount so set it with the real count of your data:
result.totalCount = salesOrderCount;
and then
return result;
Now the dxDataGrid is aware of the total count of records.

/var/www/vhosts/sahinucar.com.tr/httpdocs/wp-includes/wp-db.php on line 1890

My website is not working properly. I get this error:
/var/www/vhosts/xyz.com.tr/httpdocs/wp-includes/wp-db.php on line 1890
Following is the code on those lines. What is the problem in this code that it throws out an error?
// Return number of rows affected
$return_val = $this->rows_affected;
} else {
$num_rows = 0;
if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
**while ( $row = mysqli_fetch_object( $this->result ) ) {
$this->last_result[$num_rows] = $row;
$num_rows++;**
}
} elseif ( is_resource( $this->result ) ) {
while ( $row = mysql_fetch_object( $this->result ) ) {
$this->last_result[$num_rows] = $row;
$num_rows++;
}
}
// Log number of rows the query returned
// and return number of rows selected
$this->num_rows = $num_rows;
$return_val = $num_rows;
}
return $return_val;
}
/**

PhpSpreadsheet - get row without iterating on each cell

I'm using PhpSpreadsheet to easily read from a xls document and insert into a DB after some calculations. I succeeded using examples from the documentation, but I find it sooo complicated I'm sure I missed something and it can be done much more easily.
$worksheet = $this->getWorksheet("file.xls");
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE);
foreach ($cellIterator as $key => $cell) {
$cellValue = $cell->getValue();
if($key == 'A')
$field1 = $cellValue;
if($key == 'B') {
$dateTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
$date = $dateTime->format("Y-m-d");
}
if($key == 'C')
$field2 = $cellValue;
if($key == 'D')
$field3 = $cellValue;
if($key == 'E')
$field4 = $cellValue;
}
}
I would have expected something like $row->getCell("A")->getValue() to be available.
So... Have I missed something ?
See the docs on getting the values by column and row directly rather than testing the keys
From the example:
// Get the value from cell B5
$cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(2, 5)->getValue();
Hope that helps
Here is what I found
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load("test.xlsx");
$sheet = $spreadsheet->getSheet(0);
$nb = 0;
foreach ($sheet->getRowIterator() as $row) {
echo $sheet->getCell("A$nb")->getValue();
echo "<hr>";
$nb++;
}
You have to access somehow each cell.
Example: for the case when you don't know the dimensions of rows and columns ( ... which can have combined letters past single alphabet letters), get iteration for each row and then for each column, and in the end you can have the data parsed into multidimensional array:
$results = [];
$reader = new Xlsx(); // PhpOffice\PhpSpreadsheet\Reader\Xlsx
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load(storage_path('app/temp/' . $file));
$sheet = $spreadsheet->getActiveSheet();
foreach ($sheet->getRowIterator() as $index => $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells, even if a cell value is not set.
$row_content = [];
foreach ($cellIterator as $cell) {
array_push($row_content, $cell->getValue());
}
$results[] = $row_content;
}

How to Add Custom Columns to RadExplorer

How to Add Custom Columns to RadExplorer I Added Two Columns Date And Owner To the RadExplorer. URL For Demo.
http://demos.telerik.com/aspnet-ajax/fileexplorer/examples/applicationscenarios/customgridcolumns/defaultcs.aspx
Previous I am Getting FileName And Size When I added Two coloumn Headings By
private void AddGridColumn(string name, string uniqueName, bool sortable)
{
RemoveGridColumn(uniqueName);
// Add a new column with the specified name
GridTemplateColumn gridTemplateColumn1 = new GridTemplateColumn();
gridTemplateColumn1.HeaderText = name;
if (sortable)
gridTemplateColumn1.SortExpression = uniqueName;
gridTemplateColumn1.UniqueName = uniqueName;
gridTemplateColumn1.DataField = uniqueName;
Aspx_RadFileExplorer.Grid.Columns.Add(gridTemplateColumn1);
}
Function For ResolveRootDirectoryAsTree
<pre>
public override DirectoryItem ResolveRootDirectoryAsTree ( string xszPath )
{
PathPermissions zPathPermission = FullPermissions;
if ( xszPath.Equals ( "Document/Private" ) )
zPathPermission = PathPermissions.Read;
else if ( xszPath.Equals ( "Document/Public" ) )
zPathPermission = PathPermissions.Read | PathPermissions.Upload;
return new DirectoryItem(GetName(xszPath), GetDirectoryPath(xszPath), xszPath, GetDate(xszPath), zPathPermission, GetChildFiles(xszPath), GetChildDirectories(xszPath));
}
</pre>
Function For ResolveDirectory
public override DirectoryItem ResolveDirectory(string xszPath )
{
PathPermissions zPathPermission = FullPermissions;
if ( xszPath.Equals ( "Document/Private" ) )
zPathPermission = PathPermissions.Read;
else if ( xszPath.Equals ( "Document/Public" ) )
zPathPermission = PathPermissions.Read | PathPermissions.Upload;
DirectoryItem[] zdlDirectories = GetChildDirectories ( xszPath );
return new DirectoryItem ( GetName ( xszPath ), EndWithSlash ( GetDirectoryPath ( xszPath ) ), string.Empty, string.Empty, zPathPermission, GetChildFiles ( xszPath ), zdlDirectories );
}
private string GetName ( string xszPath )
{
if ( xszPath == null )
{
return string.Empty;
}
return xszPath.Substring ( xszPath.LastIndexOf ( '/' ) + 1 );
}
In This Function I Will Get OwnerID And Date as strings LoadDocuments().How to Display Owner ID to Owner Custom Field,And Date To Date Field
private void SafeLoadDocument ( string xszUserID )
{
try
{
DataTable zdtReturn = new DataTable();
if ( ViewState["m_DocumentTable"] == null )
ViewState["m_DocumentTable"] = EMSBLCRM.LoadDocuments( xszUserID );
zdtReturn = (DataTable)ViewState["m_DocumentTable"];
foreach (DataRow dr in zdtReturn.Rows)
{
double zdbFileSize = Convert.ToDouble(dr["fld_document_latest_attachment_size"]);
string zsztest = String.Format("{0:#,##0}", zdbFileSize);
dr["fld_document_latest_attachment_size"] = zsztest;
Convert.ToDouble(dr["fld_document_created_on"]);
string date = dr["fld_document_created_on"].ToString();
string date2 = date.Substring(0, 10);
}
Session["sesDocumentTable"] = ViewState["m_DocumentTable"];
}
catch ( Exception e )
{
Utilities.SendCrashEMail ( ref e );
}
}
Here's a link to the documentation and following is the code.
// Add a new 'custom column for the file owner'
GridTemplateColumn gridTemplateColumn2 = new GridTemplateColumn();
gridTemplateColumn2.HeaderText = "Owner Name";
gridTemplateColumn2.SortExpression = "Owner";
gridTemplateColumn2.UniqueName = "Owner";
gridTemplateColumn2.DataField = "Owner";
RadFileExplorer1.Grid.Columns.Add(gridTemplateColumn2);// Add the second column
//And the code for adding value for the file entry for the custom column.
public override DirectoryItem ResolveDirectory(string path)
{
// Update all file items with the additional information (date, owner)
DirectoryItem oldItem = base.ResolveDirectory(path);
foreach (FileItem fileItem in oldItem.Files)
{
// Get the information from the physical file
FileInfo fInfo = new FileInfo(Context.Server.MapPath(VirtualPathUtility.AppendTrailingSlash(oldItem.Path) + fileItem.Name));
// Add the information to the attributes collection of the item. It will be automatically picked up by the FileExplorer
// If the name attribute matches the unique name of a grid column
fileItem.Attributes.Add("Date", fInfo.CreationTime.ToString());
// Type targetType = typeof(System.Security.Principal.NTAccount);
// string value = fInfo.GetAccessControl().GetOwner(targetType).Value.Replace("\\", "\\\\");
string ownerName = "Telerik";
fileItem.Attributes.Add("Owner", ownerName);
}
return oldItem;
}
Hope this will be helpful for you.

Actionscript 3 - Fastest way to parse yyyy-mm-dd hh:mm:ss to a Date object?

I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings.
Does anyone know any faster ways of doing this or tips to speed up the methods?
castMethod1 takes 3673 ms
castMethod2 takes 3812 ms
castMethod3 takes 3931 ms
Code:
private function castMethod1(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var year:int = int(dateString.substr(0,4));
var month:int = int(dateString.substr(5,2))-1;
var day:int = int(dateString.substr(8,2));
if ( year == 0 && month == 0 && day == 0 ) {
return null;
}
if ( dateString.length == 10 ) {
return new Date(year, month, day);
}
var hour:int = int(dateString.substr(11,2));
var minute:int = int(dateString.substr(14,2));
var second:int = int(dateString.substr(17,2));
return new Date(year, month, day, hour, minute, second);
}
-
private function castMethod2(dateString:String):Date {
if ( dateString == null ) {
return null;
}
if ( dateString.indexOf("0000-00-00") != -1 ) {
return null;
}
dateString = dateString.split("-").join("/");
return new Date(Date.parse( dateString ));
}
-
private function castMethod3(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var mainParts:Array = dateString.split(" ");
var dateParts:Array = mainParts[0].split("-");
if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) {
return null;
}
return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) );
}
No, Date.parse will not handle dashes by default. And I need to return null for date time strings like "0000-00-00".
I've been using the following snipplet to parse UTC date strings:
private function parseUTCDate( str : String ) : Date {
var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/);
var d : Date = new Date();
d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));
d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0);
return d;
}
Just remove the time part and it should work fine for your needs:
private function parseDate( str : String ) : Date {
var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/);
var d : Date = new Date();
d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));
return d;
}
No idea about the speed, I haven't been worried about that in my applications. 50K iterations in significantly less than a second on my machine.
This was the fastest I could come up with after some fiddling:
private function castMethod4(dateString:String):Date {
if ( dateString == null )
return null;
if ( dateString.length != 10 && dateString.length != 19)
return null;
dateString = dateString.replace("-", "/");
dateString = dateString.replace("-", "/");
return new Date(Date.parse( dateString ));
}
I get 50k iterations in about 470ms for castMethod2() on my computer and 300 ms for my version (that's the same amount of work done in 63% of the time). I'd definitely say both are "Good enough" unless you're parsing silly amounts of dates.
I'm guessing Date.Parse() doesn't work?
Well then method 2 seems the best way:
private function castMethod2(dateString:String):Date {
if ( dateString == null ) {
return null;
}
if ( dateString.indexOf("0000-00-00") != -1 ) {
return null;
}
dateString = dateString.split("-").join("/");
return new Date(Date.parse( dateString ));
}
Because Date.parse() does not accept all possible formats, we can preformat the passed dateString value using DateFormatter with formatString that Data.parse() can understand, e.g
// English formatter
var stringValue = "2010.10.06"
var dateCommonFormatter : DateFormatter = new DateFormatter();
dateCommonFormatter.formatString = "YYYY/MM/DD";
var formattedStringValue : String = dateCommonFormatter.format(stringValue);
var dateFromString : Date = new Date(Date.parse(formattedStringValue));
var strDate:String = "2013-01-24 01:02:40";
function dateParser(s:String):Date{
var regexp:RegExp = /(\d{4})\-(\d{1,2})\-(\d{1,2}) (\d{2})\:(\d{2})\:(\d{2})/;
var _result:Object = regexp.exec(s);
return new Date(
parseInt(_result[1]),
parseInt(_result[2])-1,
parseInt(_result[3]),
parseInt(_result[4]),
parseInt(_result[5]),
parseInt(_result[6])
);
}
var myDate:Date = dateParser(strDate);
Here is my implementation. Give this a try.
public static function dateToUtcTime(date:Date):String {
var tmp:Array = new Array();
var char:String;
var output:String = '';
// create format YYMMDDhhmmssZ
// ensure 2 digits are used for each format entry, so 0x00 suffuxed at each byte
tmp.push(date.secondsUTC);
tmp.push(date.minutesUTC);
tmp.push(date.hoursUTC);
tmp.push(date.getUTCDate());
tmp.push(date.getUTCMonth() + 1); // months 0-11
tmp.push(date.getUTCFullYear() % 100);
for(var i:int=0; i < 6/* 7 items pushed*/; ++i) {
char = String(tmp.pop());
trace("char: " + char);
if(char.length < 2)
output += "0";
output += char;
}
output += 'Z';
return output;
}

Resources