Datetime recorded in UTC on server but to be edited in local time

Datetime recorded in UTC on server but to be edited in local time

fabioberettafabioberetta Posts: 74Questions: 23Answers: 4

Hello all,

I cannot figure which pattern I have to follow to manage dates in different timezonew with datatables editor.

This is what I have to do:
- Server stores date and time in UTC
- the client when it connects should display the date time in the client timezone.

I was hoping to use getFormatter and setFormatter to change between timezones but I could not find any example.

Any suggestion would be appreciated.

ty
f

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    I don't have any examples of using the formatters to change time zones, but it should be quite possible. You can do it in PHP using the DateTime object - see for example this SO thread.

    Regards,
    Allan

  • fabioberettafabioberetta Posts: 74Questions: 23Answers: 4
    edited May 2016

    Thanks Allan,

    I finally solved this way:

    • Database is in UTC
    • Client is in local time
    • Conversion is done in PHP using formatters

    This is the code I used. Pretty simple actually.

    Field::inst( 'log.log_date_time' )
                ->validator( 'Validate::dateFormat', array(
                        'empty' => false,
                        'format' => 'Y-m-d H:i' ))
                        
                            ->getFormatter( function ( $val, $data, $opts ) use ( $user_tz ) {
                                                                $converted_date = new DateTime($val, new DateTimeZone( 'UTC' ));
                                                                $converted_date->setTimeZone( new DateTimeZone( $user_tz ));
                                                                return $converted_date->format('Y-m-d H:i');
                                                            } )
                            ->setFormatter( function ( $val, $data, $opts ) use ( $user_tz ) {
                                                                $converted_date = new DateTime($val, new DateTimeZone( $user_tz ));
                                                                $converted_date->setTimeZone( new DateTimeZone( 'UTC' ));
                                                                return $converted_date->format('Y-m-d H:i:s');
                                                            } ),
    
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Looks good - thanks for posting back with your code!

    Allan

This discussion has been closed.