Time and Calendars in Salesforce: How to Avoid Misunderstandings with Localization

Time and Calendars in Salesforce: How to Avoid Misunderstandings with Localization

Have you ever dreamed of traveling through time?

I'm sure most of us have thought about it. Many of us enjoy the Back to the Future movie series with the charismatic Doc and the clever Marty McFly, right?

What if I told you that you can travel through time with Salesforce?

Yes, yes, from 2025 – straight to the year 1482.

You might think: "What kind of nonsense is this?"

Let’s take a closer look at this issue.

This week, I came across an interesting question in the Trailblazer Community:

"When executing the code Datetime.valueOf('2025-01-23 17:47:00'), the result was 1482-01-23 09:47:00, locale – Thai (Thailand)".

It really is strange, how did we end up in 1482 from 2025? =)

As it turns out, it’s much simpler than that.

Since Thailand uses the Buddhist calendar, which is 543 years different from the Gregorian calendar, by setting the locale to Thai in SF, we will be in the year 1482, not 2025.

Therefore, when writing certain scenarios, such aspects need to be considered.

How is this resolved?

1. We can simply add 543 years to our result, that is:

For example, let's execute the following code:

Datetime dt = Datetime.valueOf('2025-01-23 17:47:00');
System.debug(dt);        

Result:

Let's make adjustments to our code:

Datetime dt = Datetime.valueOf('2025-01-23 17:47:00');
if (UserInfo.getLocale() == 'th_TH') {
    dt = dt.addYears(543);
}
System.debug(dt);        

Checking:

2. The second method is more complex, we can explicitly specify the time zone and set the year.

String dateStr = '2025-01-23 17:47:00';
// Splitting a string into date and time
String datePart = dateStr.split(' ')[0];
String timePart = dateStr.split(' ')[1];
// We break time into hours, minutes, and seconds.
List<String> timeParts = timePart.split(':');
Integer hours = Integer.valueOf(timeParts[0]);
Integer minutes = Integer.valueOf(timeParts[1]);
Integer seconds = Integer.valueOf(timeParts[2]);
// Create object Time
Time timeInstance = Time.newInstance(hours, minutes, seconds, 0);
// Convert date to DateTime in GMT time zone
DateTime dt = DateTime.newInstanceGMT(Date.valueOf(datePart), timeInstance);
System.debug('Converted Datetime: ' + dt);        
Conslusion

Time travel with Salesforce is indeed possible if we take into account the peculiarities of localizations and calendars, such as the Buddhist calendar in Thailand. Clearly, using different time zones and calendar systems can lead to unpredictable results. However, by being aware of these nuances, we can adjust the time and date in our solutions. This highlights the importance of localization settings and accurately considering time zones when working with dates and times in Salesforce.

要查看或添加评论,请登录

Mykhailo Vdovychenko的更多文章

社区洞察

其他会员也浏览了