Skip to content

Instantly share code, notes, and snippets.

@renatoliveira
Last active January 29, 2019 10:50
Show Gist options
  • Save renatoliveira/2d25ac391d3eb780200c7600bd42ea19 to your computer and use it in GitHub Desktop.
Save renatoliveira/2d25ac391d3eb780200c7600bd42ea19 to your computer and use it in GitHub Desktop.
This gist shows that you can use the 'runAs' method to simulate timezone differences between one or more users in a test.
// Considering that 'neutral_user' has 'GMT' as its 'TimeZoneSidKey' field,
// and that the other two users run with 'America/Puerto_Rico' and
// 'America/Sao_Paulo'.
Datetime christmas2018utc;
System.runAs(neutral_user) {
// Creates a datetime instance on December 25th, at 12:00 (GMT).
// Using the 'runAs' method because if we don't, then the date instance will be
// on the same timezone as the test running user.
christmas2018utc = Datetime.newInstance(Date.newInstance(2018, 12, 25), Time.newInstance(12, 0, 0, 0));
}
TimeZone mtz = Timezone.getTimeZone('America/Puerto_Rico'); // UTC-4
TimeZone btz = Timezone.getTimeZone('America/Sao_Paulo'); // UTC-3 (UTC-2 if on DST)
Datetime now = Datetime.now();
Integer m_diff = (mtz.getOffset(now) / 3600000);
Integer b_diff = (btz.getOffset(now) / 3600000);
System.runAs(manaus_user) {
// In Manaus (Brazil) the timezone is UTC-4, so the hour value will be 8.
System.debug('For the Manaus user, the time is ' + (12 + m_diff));
System.assertEquals(12 + m_diff, christmas2018utc.hour());
}
System.runAs(minas_user) {
// In Belo Horizonte (Brazil) the timezone is UTC-2 (DST), so the hour value will be 10.
// If it is not on DST, then it will be UTC-3, and the hour value would be 9.
System.debug('For the Belo Horizonte user, the time is ' + (12 + b_diff));
System.assertEquals(12 + b_diff, christmas2018utc.hour());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment