Salesforce LWC学习(四十四) Datatable 显示日期类型的有趣点思考

salesforce,lwc,学习,四十四,datatable,显示,日期,类型,有趣,思考 · 浏览次数 : 187

小编点评

## Summary of the content This Lightning Web Component (LWC) code demonstrates how to display date fields in a specific format based on the user's location. It uses the `lightning-formatted-date-time` attribute to achieve this. Here's a breakdown of the key points: **Date format:** * The code uses `lightning-formatted-date-time` to parse the date value and display it in a user-friendly format. * The `typeAttributes` attribute allows specifying additional attributes like `day`, `month`, `year`, `hour`, `minute`, and `hour12`. * By setting the `timeZone` attribute to the user's current location, the date is displayed in the specified format based on their timezone. **User's locale and time zone:** * The code uses the `timeZone` attribute to access the user's configured locale and time zone. * This ensures that the date is displayed in the user's preferred format, even if they are in a different time zone. **Issues with date format:** * The original code used `salesforce`'s default locale, which might not match the user's actual location. * This caused the date to be displayed in a different format depending on the user's location. **Improvements:** * The revised code sets the `timeZone` attribute to the user's configured location. * This ensures that the date is always displayed in the specified format, regardless of the user's location. **Conclusion:** By addressing the date format issue, this LWC provides a more accurate and consistent way to display date fields based on the user's location.

正文

本篇参考:https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_salesforce_modules

背景: 项目中经常用到datatable显示日期类型字段,并要求日期类型字段基于指定格式显示。这种是一个很常见的需求,而且demo很容易找到,无论是官方文档中还是网上。这里列一个简单的demo,因为apex只是获取数据比较简单,这里不做显示,只列出关键内容。

contactListSample.js

import { LightningElement, track,wire } from 'lwc';
import findContacts from '@salesforce/apex/ContactControllerForDay7.findContacts';

export default class ContactListSample extends LightningElement {

    @track contacts;
    @track errors;

    columns = [

      {
        type: "text",
        fieldName: "Name",
        label: "Contact Name"
      },
      {
        type: "date",
        fieldName: "CreatedDate",
        label: "Created Date",
        typeAttributes:{day:'numeric',month:'numeric',year:'numeric',
          hour:'2-digit',minute:'2-digit',hour12:true
        }
      }];


    @wire(findContacts)
  wiredContacts({data,error}) {
    if(data) {
        this.contacts = data;
        this.errors = undefined;
        console.log('execute success');
    } else if(error) {
        this.errors = error;
        this.contacts = undefined;
        console.log('execute failed');
    }
  }
}

contactListSample.html

<template>
    <lightning-datatable columns={columns} data={contacts} key-field="Id">
    </lightning-datatable>
</template>

效果显示:以指定格式显示。

问题:这里我们需要对日期类型显示进行一个思考。官方文档介绍,datatable针对日期类型的渲染,使用的是lightning-formatted-date-time进行解析。问题来了,当对日期进行解析时,使用的是salesforce中的user的 locale setting还是用户当前的地区的本地时区设置呢?曾几何时,因为官方的文档没太读懂以及英语不太好,有了一些误解,认为获取的是salesforce中的user setting的timezone,其实不然,官方的默认行为获取的是当前用户当前访问的电脑设置的本地时区的设置。我们可以看一下相关的截图。上个截图中显示时间是曾经我在中国区GMT+8的时间显示,现在我修改成 GMT-4 美国时间。

 上图的datatable还是没有变化。但是详情页却相差了12小时时差。

这种场景在实际的使用中很难存在,因为实际的user大部分场景应该和所在地保持一致,即salesforce的user setting所配置的locale以及timezone会和本地保持一致,但是有种特殊场景,比如call center在国外,倒班有时差,需要配合客户的时间,需要将自己的salesforce账户的时间配置转换成客户时区,那这里就会出现这样的问题了。那如何修复呢? salesforce给我们预留了功能,只需要传递一下当前用户的salesforce中配置的地址时区即可。我们修改一下js部分代码:

import { LightningElement, track,wire } from 'lwc';
import findContacts from '@salesforce/apex/ContactControllerForDay7.findContacts';
import timeZone from '@salesforce/i18n/timeZone';
export default class ContactListSample extends LightningElement {
    @track contacts;
    @track errors;

    columns = [

      {
        type: "text",
        fieldName: "Name",
        label: "Contact Name"
      },
      {
        type: "date",
        fieldName: "CreatedDate",
        label: "Created Date",
        typeAttributes:{day:'numeric',month:'numeric',year:'numeric',
          hour:'2-digit',minute:'2-digit',hour12:true,timeZone:timeZone
        }
      }];


    @wire(findContacts)
  wiredContacts({data,error}) {
        if(data) {
            this.contacts = data;
            this.errors = undefined;
            console.log('execute success');
        } else if(error) {
            this.errors = error;
            this.contacts = undefined;
            console.log('execute failed');
        }
    }
}

改动上述位置以后的结果显示:已经基于具体的salesforce中配置的timezone进行显示时间。

总结: 本篇实际使用场景可能仅适用于用户实际时区和配置时区不同的优化方案,大部分场景并不会有问题,篇中有错误欢迎指出,有不懂欢迎留言。

与Salesforce LWC学习(四十四) Datatable 显示日期类型的有趣点思考相似的内容:

Salesforce LWC学习(四十四) Datatable 显示日期类型的有趣点思考

本篇参考:https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_salesforce_modules 背景: 项目中经常用到datatable显示日期类型字段,并要求日期类

Salesforce LWC学习(四十) datatable的dynamic action的小坑浅谈

本篇参考:https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/documentation 我们在项目中会用到针对table等显示 dynamic action的情况,即基于每行的特有属性

Salesforce LWC学习(四十五) lwc支持Console App控制Tab了

本篇参考:https://help.salesforce.com/s/articleView?id=release-notes.rn_lwc_workspaceAPI.htm&release=246&type=5 https://developer.salesforce.com/docs/compo

Salesforce LWC学习(四十) dynamic interaction 浅入浅出

本篇参考: Configure a Component for Dynamic Interactions in the Lightning App Builder - Salesforce Lightning Component Library Salesforce Help | Article G

Salesforce LWC学习(四十一) If:true 即将弃用?

本篇参考: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_directiveshttps://developer.salesforce.com/docs/compo

Salesforce LWC学习(四十二) getRecordNotifyChange已弃用

本篇参考: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_get_record_notify https://developer.salesforce.com/do

Salesforce LWC学习(四十三) lwc 零基础学习路径的视频已上传B站

本篇参考:https://www.bilibili.com/video/BV1QM411G7pN/ 还记得salesforce零基础学习(一百二十五)零基础学习SF路径 中描述的那样,预计今年年底以前基于0基础学习的内容录制成视频,更好的更方便的进行学习和互动。当时的一个动机是以前公司做veeva的

salesforce零基础学习(一百三十六)零碎知识点小总结(八)

本篇参考: Salesforce LWC学习(七) Navigation & Toast https://developer.salesforce.com/docs/platform/lwc/guide/use-navigate-url-addressable.html https://help.s

salesforce零基础学习(一百三十八)零碎知识点小总结(十)

本篇参考: https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_5level_SOQLqueries.htm&release=250&type=5 https://developer.salesforce.com/to

salesforce零基础学习(一百三十七)零碎知识点小总结(九)

本篇参考: https://help.salesforce.com/s/articleView?id=release-notes.rn_lab_conditional_visibiliy_tab.htm&release=250&type=5 https://help.salesforce.com/s