I'm working on a Dashboard/Analytics project where different regions 
(Component sub-trees) on the same page could be in different timezones.

This is an idea I wanted to share for dealing with timezone conversion:

@Pipe({name: 'tzFormat'})
export class MomentTimezoneFormatPipe implements PipeTransform {


  constructor(private timezoneService: TimezoneService) {}


  transform(value: Date, format: string, timezone: string): string {
    if (timezone == null) {
      // get timezone from provider
      timezone = this.timezoneService.timezone;
    }
    return moment(value).tz(timezone).format(format);
  }
}

In templates, you can do:

{{myDate|tzFormat:'MMM D HH:mm':'America/Los_Angeles'}}

Or bind to the Component's timezone field
{{myDate|tzFormat:'MMM D HH:mm':myTimezone}}

However, it gets annoying to pass the timezone to multiple Components. So 
instead, the parent component can provide the *TimezoneService*:
*Of course this should be extended to validate the timezone, provide the 
offset, etc.*

@Injectable()
export class TimezoneService {
  timezone: string;
}

The highest Component associated with the timezone creates the provider and 
sets the timezone.
@Component({
// normal component stuff...
  providers: [TimezoneService]
})
export class ParentComponent implements OnInit {

  @Input() timezone: string;

  constructor(public timezoneService: TimezoneService) {}

  ngOnInit() {
    this.timezoneService.timezone = this.timezone;
  }
}
*I haven't tested two instances with different timezones yet, but it should 
work.*

Now in child components anywhere in the Component subtree you can omit the 
timezone, the tzFormat pipe will get it from the *TimezoneService*.
{{myDate|tzFormat:'MMM D HH:mm'}}


Any thoughts on this design?
Does the Angular2 project have any plans to support timezones in some 
fashion?
Should I share this code as a project so people don't have to reinvent the 
wheel all the time? Is there a similar existing project?
One issue is that it's tied to moment-timezone, so a public project would 
need some way of switching timezone implementations.




-- 
You received this message because you are subscribed to the Google Groups 
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to