Typo3 6.2.15 DateTime off by 1 hour - datetime

I have a model with a DateTime column named "fromDate":
/**
* fromDate
*
* #var \DateTime
*/
protected $fromDate;
now I need this date to do some calculations, but when I try outputting it, it seems to be off exactly 1 hour.
echo $model->getFromDate()->format('Y-m-d H:i:s');
This returns 2016-02-11 01:00:00 instead of 2016-02-11 00:00:00
I checked my server timezone, date_default_timezone_get() returns "Europe/Berlin" (which is correct). I tried to change the typo3 serverTimeZone (I tried 0 and 1, but doesn't change anything).
If I look at the database with phpmyadmin, the entry is "2016-02-11 00:00:00"
What am I missing, why is this happening? Any hints? Because I feel like I'm going insane, a huge calculation script is based on the correctness of $fromDate ... Any help would be greatly appreciated. Thank you!

Try something like
$myDate = $model->getFromDate();
$myDate->setTimezone(new \DateTimeZone('UTC'));
or whatever time zone you use in your raw database table value, if not UTC.
In TYPO3 6.2, at least, doing a findAll() on your repository begins a series of calls -- to \TYPO3\CMS\Extbase\Persistence\Repository->createQuery(), and afterward to \TYPO3\CMS\Extbase\Persistence\Generic\QueryResult->rewind(). rewind() calls initialize(), which calls \TYPO3\CMS\Extbase\Persistence\Generic\Mapper->map(). map() calls mapSingleRow(), which then calls thawProperties() in the same class.
TYPO3\CMS\Extbase\Persistence\Generic\Mapper->thawProperties() has a "switch case" code section based on each property data type. If the type is DateTime, thawProperties() calls mapDateTime() in the same class.
mapDateTime() assumes "native date/datetime values are stored in UTC", so it applies the 'UTC' DateTimeZone to the raw value. But then, mapDateTime() applies the DateTimeZone from the PHP date_default_timezone_get() function, and returns the altered date and timezone property values to thawProperties() and eventually to your Extbase extension.
You can find details in the TYPO3 6.2 API reference for mapDateTime() and its definition in DataMapper.php.
My answer is related to this StackOverflow answer, this TYPO3 Forum thread, and this TYPO3 Forum thread.

This is a problem in the DateTime handling of Extbase, which was recently fixed for TYPO3 7.6 and 8 (dates were not interpreted as UTC). We won’t backport the fix for 6.2 officially, but you can of course apply it yourself.
If you don’t want to patch the core, you can also create an extension class for the relevant part (DataMapper) and override the method (mapDateTime()).

Related

Why does AliceBundle Fixture DateTime give me an unexpected value?

I'm currently working on a project in which I create fixtures with Alice-bundle to run tests to make sure my API-endpoints work properly. Everything works fine, except for the DateTime properties.
No matter what string I pass it, eg: <dateTime('2019-09-23 14:00:00')>, it always gives me the wrong date and time, usually something like: 1998-10-25T14:29:45+01:00.
Even using <dateTime('now')> does not work -- it gives me some pre-2000s date & time as well, while that's exactly what some examples I'd found do use.
A fixture could look something like this:
Path\To\Task\Entity:
my_task:
title: 'My tasks'
description: 'These are all the tasks just for me!!!'
startsAt: <dateTime('now')>
endsAt: <dateTime('now')>
createdBy: '#some_higher_user'
Ideally I just want to pass it a string so I can define both a Date and Time and make sure it works properly, in the right format.
And help would be appreciated.
Looking here https://github.com/nelmio/alice/blob/master/doc/advanced-guide.md#functions we read:
function can be a Faker or a PHP native (or registered in the global scope) function.
So I would recommend trying a PHP native function that creates a \DateTime object
<date_create_from_format ( 'Y-m-d H:i:s' , '2019-09-23 14:00:00')>
// or
<date_create('now')>
That's how it works. The <dateTime()> function takes an argument called $max. So what it does is create a date between a starting date (not sure which one, probably something in the 1900 range or so) and that $max argument.
I guess you will want to use <dateTimeBetween()> which takes a startDate and an endDate to create a fake date between them. So I suppose if startDate = endDate, then you'll get the desired fixed date.
Take a look at fzaninotto/Faker library documentation. It's the library used by AliceBundle to actually fake data. There you can see what DateTime related functions you can use.

CakePHP: FrozenTime from database without timezone

I'm on "Europe/Rome":
debug(new \Cake\I18n\Time());
Output:
object(Cake\I18n\Time) {
'time' => '2016-03-23T14:18:17+01:00',
'timezone' => 'Europe/Rome',
'fixedNowTime' => false
}
If I save a post (for example), the datatime is handled properly.
The problem occurs when I retrieve data. This post has been just saved:
debug($post->created);
Output:
object(Cake\I18n\FrozenTime) {
'time' => '2016-03-23T14:14:45+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
}
The datetime is correct, but the timezone of course not.
Now if I do something like this:
debug($post->created > new \Cake\I18n\Time());
the result will obviously be TRUE and not FALSE (as it should be). I conclude that this happens because, in comparison phase, it obviously uses the same timezone.
Where am I doing wrong? Thanks.
EDIT
My bootstrap.php
date_default_timezone_set('UTC');
Instead, my php.ini (I think it's not relevant):
date.timezone = Europe/Rome
So I have to think that the value of $post->created is correct.
But now... why new \Cake\I18n\Time() uses the correct timezone (which is not set) and why the post is saved with the correct timezone?
I would kinda doubt that new \Cake\I18n\Time() will use the timezone set in your INI after date_default_timezone_set() has been used, as the latter should win over the former. Maybe there's a version specific behavior/bug where this doesn't work as expected, not sure, you'll have to debug your environment to figure what's going on there.
That being said, when data is being read, the ORM casts it to PHP datatypes. The date/time type classes responsible for this are using cloned date/time class instances instead of creating new ones, and that base instance is created when the type instance is first built and/or when the mutability is being set, which usually happens at bootstrapping time when Type::build() is invoked.
If you'd then for example change the timezone at a later point, new \Cake\I18n\Time based instances would use the newly set timezone, but the date/time type would still use the instance that was created with the original timezone at bootstrapping time.
tl;dr
Set the proper timezone via date_default_timezone_set() in your bootstrap, and if you need to change the timezone at a later point, then you'll have to make sure that a new base type instance for cloning is being set, which could for example be done by setting the mutability again, like
Type::build('time')->useImmutable();
This feels kinda workaroundish though, you may want to open a ticket over at GitHub and report this behavior.

How to properly output DateTime with TYPO3 extbase fluid

I got two dateTime Objects stored in the Database:
2014-11-03 09:00:00
2014-10-21 13:45:00
When i try to output them with the ViewHelper format.date
<f:format.date format="H:i">{termin.datumBeginn}</f:format.date>
I get the following results:
10:00
15:45
So i got a one hour shift and a two hour shift which i can't write a workaround for. How do i set the timezones properly to have a clean output?
Although this is very old, I want to highlight that this was a bug in Extbase until recently, and we fixed it in TYPO3 7.6 and 8. The dates are now properly read as UTC, as which they are stored in the database, and converted to your server timezone.
Ensure that all dates in you database are in same timezone, because that information is not saved there. When you receive some objects from external API calls, they will have timezone in date string and it will be usually UTC. From your internal calls all \DateTime objects will use by default your server default timezone. So set timezone before saving it to database:
$receivedDate = new \DateTime($date);
$reveivedDate->setTimezone(new \DateTimeZone(date_default_timezone_get()));
Setting timezone to server default is convenient, because requires no more changes.. but it's better to save it in 'UTC' I think. In that case you will need to convert it back to your server/user timezone before showing it. It can be done in ViewHelper (not default one from Typo3.Fluid but you can easily extend it in your package - clone and set timezone again). Maybe it's possible now to use doctrine extensions in flow, and save timezone with date to database.. i tried it year ago and couldn't make it..
To solve this issue you need to set $TYPO3_CONF_VARS['SYS']['phpTimeZone'] as "UTC" and $TYPO3_CONF_VARS['SYS']['serverTimeZone'] as "0" (probably only first setting will be enough). You can do it through typo3 backend, using Install tool.
If you have domain model you can use a workaround:
/**
* Returns the startDate
*
* #return \DateTime|NULL $startDate
*/
public function getStartDate() {
$date = $this->startDate;
if($date) {
$date->setTimezone(new \DateTimeZone('UTC'));
}
return $date;
}
Please make sure that you have put setting the Timezone for PHP in the php.ini file
Example: date.timezone = "Asia/Phnom_Penh"
For more information of PHP Timezone please refer to this link: http://php.net/manual/en/timezones.america.php

XPages: create current Datetime in ssjs and save to a Datetime Notes form field

The only way i have found to store date in a Datetime field in a notes form is this:
theDoc2.replaceItemValue("lastAccess",session.createDateTime("Today"));
But this only creates a Date, not DateTime. Also, i dont want to create a static time like "Today 12" but i want the current datetime dynamicly.
Using this i get an error (Exception occurred calling method NotesDocument.replaceItemValue(string, Date) null):
theDoc2.replaceItemValue("lastAccess",#Now());
and using this, the form field changes from Date/Time to Text data type and i want to keep Date/Time type:
theDoc2.replaceItemValue("lastAccess",#Now().toLocaleString);
Any ideas?
Just gave it a try:
as you wrote, .replaceItemValue("fieldName", #Now()) throws an error.
However, I got it to work with
.replaceItemValue("fieldName", session.createDateTime(#Now()))
In that case the value is stored in the Notes field as Time/Date with all necessary components as in
17.01.2014 12:45:51 CET
From what I can see, difference between the two is that #Now() returns a Date data type, whereas session.createDateTime() returns a NotesDateTime object
On the other hand, for me it's also working with your original method:
session.createDateTime("Today")
Don't know what's causing the prob on your side; do you have an editable represantion of the field on you xpage? If so, does it have some kind of converter enabled which could do some filtering during submit?
i will answer my own question as i found a way. Please comment if you think it is not correct or best practice...
theDoc2.replaceItemValue("lastAccess",session.createDateTime("Today"+#Now().toLocaleTimeString()));
A little late, but I had the same problem, but this method resolved it:
DateTime datumtijd = session.createDateTime("Today");
datumtijd.setNow(); //!!!!!!
System.out.println((datumtijd).toString());
Hope it helps :)

Dexterity Content Type DateTime Issue & How to modify Content Type Values

First of all: I am running a Plonce Plone 4.3 (4305) instance with Dexterity Content Types 2.0.7
My approach is to write a Python Script (added via ZMI) which creates my dexterity content type using the methods invokeFactory(...) or typestool.constructContent(..) described here: http://plone.org/documentation/kb/add-content-programmatically (I've written two scripts which do the same task but use different methods - for learning purposes)
Everything is working fine, except when i try to add a DateTime Object to the constructor of both methods above to create my Content Type. The Date field strangly only updates the day and year values. Because of the restrictions in importing libraries inside python i am stuck (with my current knowledge) with this code:
d = DateTime('12/12/2013')
My script returns the date object after completion which looks like this:
2013/12/12 00:00:00 GMT+1
I've written another small script which outputs the Date value after construction and it gives me the same result (which seems to be correct). The resulting Content Type has its day and year field updated correctly but the month value stays on January and raises the following TypeError upon viewing:
TypeError: int() argument must be a string or a number, not 'instancemethod'
I can fix this by editing the month value manually which is not exactly what i want. I guess it its a minor problem with my DateTime object but i am running out of ideas at this point (overall documentation seems to be a bit scattered). I've tried various date formats inside the DateTime constructor but without luck.
I am also not sure how to modifiy my objects custom field values. Plone seems only to provide setTitle() and setDescription() methods. Maybe someone has a good hint.
Thanky you all in advance,
regards
not sure about the dateTime issue, but check out indexes, indexing and custom index to figure out setting titles and description.
to set your title for instance
#indexer(IFormName)
def titleIndexer(obj):
return obj.valueFromForm
grok.global_adapter(titleIndexer, name="Title")
AFAIK, the problem is that DateTime field for dexterity types needs a datetime object, not a DateTime object.
In the invokeFactory, you should pass a datetime object instead of a DateTime object
>>>date=datetime.datetime(2011,1,1)
>>>myobj=target.invokeFactory(type_name="content_type_name", id=id, date=date)
>>from DateTime import DateTime
>>DateTime().month()
7
>>from datetime import datetime
>>datetime.now().month
7
>>datetime.now().month()
TypeError: 'int' object is not callable
>>> myobj.date
datetime.datetime(2013, 7, 26, 0, 0)
>>> myobj.date.month
7
>>> myobj.date.month()
TypeError: 'int' object is not callable

Resources