本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前言
在Salesforce中,Date和DateTime值是以GMT形式存储在DB中,我们可以使用apex:outputText标签输出GMT格式的Date和DateTime,这样一来,如果我们在开发中忽略时区这一概念,就会出现问题,特别是当GTM格式的DateTime为:27/04/2020 00:00这种0时。本篇旨在在VFP中解决日期或时间格式化的问题。
问题展示
解决方案
date / datetime + offset(double)
public class TimeZoneController {
public TimeZoneController() {
}
public Double offset {
get{
TimeZone tz = UserInfo.getTimeZone();
//Milliseconds to Day
return tz.getOffset(DateTime.now()) / (1000 * 3600 * 24.0);
}
}
}
<apex:page controller="TimeZoneController">
<br/>
<br/>
<h2>Now without offSet</h2><br/>
<apex:outputText value="{0,date,dd/MM/yyyy HH:mm:ss}">
<apex:param value="{!NOW()}"/>
</apex:outputText>
<br/>
<br/>
<h2>Now with offSet</h2><br/>
<apex:outputText value="{0,date,dd/MM/yyyy HH:mm:ss}">
<apex:param value="{!NOW()+offset}"/>
</apex:outputText>
<br/>
<br/>
<h2>Format DateTime</h2><br/>
<apex:outputText value=" {0,date,d MMM yyyy}">
<apex:param value="{!NOW()+offset}"/>
</apex:outputText>
<br/>
<br/>
<h2>Format Date</h2><br/>
<apex:outputText value=" {0,date,d MMM yyyy}">
<apex:param value="{!TODAY()+offset}"/>
</apex:outputText>
</apex:page>
效果预览
参考资源
Display DateTime with TimeZone in Visualforce Page
Date format and DateTime format