Вот рабочая версия. Я изменил маркировки XmlElementAttribute на XmlElement, потому что в xml StockNumber, Сделайте, и Образцовые значения являются элементами, не атрибутами. Также я удалил читателя. ReadToEnd (); (что функция чтения целый поток и возвраты строка, таким образом, Deserialze () функция не могла использовать читателя больше... положение, была в конце потока). Я также взял несколько свобод с именованием:).
Вот классы:
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlElement("StockNumber")]
public string StockNumber { get; set; }
[System.Xml.Serialization.XmlElement("Make")]
public string Make { get; set; }
[System.Xml.Serialization.XmlElement("Model")]
public string Model { get; set; }
}
[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
[XmlArray("Cars")]
[XmlArrayItem("Car", typeof(Car))]
public Car[] Car { get; set; }
}
Десериализовывать функция:
CarCollection cars = null;
string path = "cars.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
И немного настроенный xml (я должен был добавить новый элемент для обертывания < Cars>... сеть требовательна в отношении десериализации массивов):
1020
Nissan
Sentra
1010
Toyota
Corolla
1111
Honda
Accord
Есть много проблем с часовыми поясами и переходом на летнее время при использовании базовой арифметики для расчета времени. Лучшее решение - полагаться на собственные функции даты и времени PHP, такие как strtotime () или mktime () . Я писал о проблемах с переходом на летнее время в своем блоге .
echo date('Y-M-d H:i:s', strtotime('2009-07-14 02:00:00 + 13 hours'));
У вас есть таблица с отметками времени? Если это база данных MySQL, вы можете просто сделать это в базе данных, используя addtime : SELECT ADDTIME ('2007-12-31 23: 59: 59.999999', '1 1: 1: 1.000002' );
Если вы используете PHP Zend Framework, вы можете сделать что-то вроде:
$date=new Zend_Date(Array('year'=>$iYear,'month'=>$iMonth,'day'=>$iDay));
// changes $date by adding 12 hours
$date->add('12:00:00', Zend_Date::TIMES);
В качестве альтернативы вы можете сделать это, используя собственные функции PHP4, такие как: [быстрее, менее точно: без учета дополнительных секунд / изменений часового пояса и т. д.]
$datestamp=strtotime('2009-07-14 02:00:00'); // It'll probably be better using mktime
$datestamp=$datestamp+(60*60*13); // 60 seconds times 60 minutes times 13 hours
или [медленнее, точнее]
$datestamp = strtotime('2009-07-14 02:00:00'); // It'll probably be better using mktime
$newDate = date('Y-m-d H:i:S', mktime(date('H',$datestamp)+13, date('i',$datestamp), date('s',$datestamp), date('m',$datestamp), date('d',$datestamp), date('Y',$datestamp)));
или, если вы используете PHP 5, используя Datetime functions
$date = new DateTime('2009-07-14 02:00:00');
date_add($date, new DateInterval("P13H"));
I know that
date( "Y-M-d H:i:s", strtotime( $timestamp_from_array ) + 13 * 3600 );
is smelly, but it will give you an idea.
strtotime
converts the timestamp string to a timestamp value, then we add the hours and convert it back to the timestamp format in the array with the date
function.
But I suppose what you really want is to use time zones.
Edit: igstan is correct, you should also mind the daylight saving time changes between those offsets.
Can you do the add as it comes out of the database?
SELECT ... DateAdd(hh, 13, DateField) AS DateField
(SQL Server)
you could use http://de3.php.net/manual/en/function.strptime.php to convert it to a unix timestamp. Then you could easily add 13*60*60 to that and use http://de3.php.net/manual/en/function.date.php to convert it back to a timestamp as you like.
another way would be via the explode function, but i think this might be more complicated because you have to look if days/month/years change and stuff
<?php
echo date('Y-m-d H:i:s', strtotime('+13 hours', strtotime('2009-07-14 02:00:00')));
?>