簡體   English   中英

如何將來自服務器的日期格式化為客戶端機器的日期格式?

[英]How can I format the date coming from the server to date format of client machine?

我在我的 web 頁面上使用 react.js,我想知道如何獲取服務器的日期並根據客戶端的國家/地區格式放置它。

示例:服務器生日:2002-22-12 我想要的生日,如果客戶是巴西人:22/12/2002

謝謝。

我看過其他關於日期的問題,但他們只是獲取真實日期並對其進行格式化。 我需要從 API/后端獲取它。

在客戶端處理日期時(無論我使用哪種框架)——我總是使用 moment.js package https://momentjs.com/

那是0依賴的純js庫,所以一方面可以和任何前端技術對接,另一方面可以用少量的代碼輕松實現任何日期相關的操作,fe

moment().format('MMMM Do YYYY, h:mm:ss a');

對於以當前語言環境格式格式化日期的特定情況,您只需執行以下操作:

let date = Date.now();
let dateMoment = moment(date);
console.log(dateMoment.format('L')); // 01/06/2023

如果您想將所有日期格式化為非當前語言環境,請明確更改它,我參考了這篇文章Locale detection with Moment.js

moment.locale('ar');

let yourDateVariable = Date.now();
let yourDateMoment = moment(yourDateVariable);

console.log(yourDateMoment.format()); // ٢٠٢٣-٠١-٠٦T١٦:٣٤:١٩+٠٣:٠٠

最后,要獲取當前瀏覽器區域設置(如果需要),請嘗試以下操作:

var locale = window.navigator.userLanguage || window.navigator.language;

最初,最佳做法是以 ISO-8601 格式YYYY-MM-DDTHH:mm:ss.sssZ從服務器獲取日期。 這有助於我們更好地處理日期。

現在,原生的Intl API有很好的瀏覽器支持,我們可以很容易地使用它來實現:

const dateInIsoFormatFromServer = "2022-06-03T19:38:34.203Z";
const date = new Date(dateInIsoFormatFromServer);

const formatter1 = new Intl.DateTimeFormat("en-US");
console.log("Format for United States locale: ", formatter1.format(date));
// Format for United States locale:  6/3/2022 

const formatter2 = new Intl.DateTimeFormat("pt-BR");
console.log("Format for Brasil locale: ", formatter2.format(date));
// Format for Brasil locale:  03/06/2022 

const formatter3 = new Intl.DateTimeFormat("es-AR");
console.log("Format for Argentina locale: ", formatter3.format(date));
// Format for Argentina locale:  3/6/2022 

此處的區域設置字符串可以從服務器發送到Intl.DateTimeFormat方法中進行設置。 但是,您可以使用導航器 object 從用戶瀏覽器獲取區域設置,並將該區域設置動態地設置為格式化程序:


const dateInIsoFormatFromServer = "2022-06-03T19:38:34.203Z";
const date = new Date(dateInIsoFormatFromServer);

const browserLocale =
  window.navigator.language || window.navigator.browserLanguage;

const formatter1 = new Intl.DateTimeFormat(browserLocale);
console.log("Format for browser locale: ", formatter1.format(date));
// Format for browser locale:  03/06/2022 
// * My browserLocale is pt-BR

如有必要,您可以設置選項來自定義格式 output:


const dateInIsoFormatFromServer = "2022-06-03T19:38:34.203Z";
const date = new Date(dateInIsoFormatFromServer);

const browserLocale =
  window.navigator.language || window.navigator.browserLanguage;

const options = {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  hour12: false
};
const formatter1 = new Intl.DateTimeFormat(browserLocale, options);
console.log("Format for browser locale with options: ", formatter1.format(date));
// Format for browser locale with options:  03/06/2022 12:38:34 
// * My browserLocale is pt-BR

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM