根據使用者係統時區動態展示時間
當我們使用SpringBoot Mysql開發系統時,總是統一設定UTC 8時區,這樣使用者在任何地區存取系統,展示的時間都是國內標準時間,體驗不友好,下面透過取得目前使用者係統所在的時區,給使用者展示不同的時間。
一、使用者時區的取得
我們可以透過JavaScript來取得系統所在的時區,然後統一設定在請求頭裡。
Intl.DateTimeFormat().resolvedOptions().timeZone; // Asia/Shanghai
二、核心程式碼
這裡統一使用LocalDateTime,更方便的處理時區轉換問題,透過識別目前LocalDateTime物件所屬時區,然後轉換為目標時區時間。
public LocalDateTime convertLocalDateTime(LocalDateTime localDateTime, ZoneId originZoneId, ZoneId targetZoneId) { return localDateTime.atZone(originZoneId).withZoneSameInstant(targetZoneId).toLocalDateTime(); }
三、SpringBoot返回json時統一處理時區
當程式從資料庫中讀取出並轉換成LocalDateTime對象,並經過業務邏輯處理,這時候該對象還是屬於UTC 8時區,對應的ZoneId=Asia/Shanghai,當需要返回給前端時,可以透過自訂jackson序列化器,在LocalDateTime轉json前轉換到使用者目標時區。
@Configuration public class JacksonConfiguration { @Autowired private JacksonProperties jacksonProperties; /** * 时区转换 * * @param localDateTime * @param originZoneId * @param targetZoneId * @return */ public static LocalDateTime convertLocalDateTime(LocalDateTime localDateTime, ZoneId originZoneId, ZoneId targetZoneId) { return localDateTime.atZone(originZoneId).withZoneSameInstant(targetZoneId).toLocalDateTime(); } /** * LocalDateTime序列化 */ public static class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { private DateTimeFormatter formatter; public CustomLocalDateTimeSerializer(DateTimeFormatter formatter) { super(); this.formatter = formatter; } @Override public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeString(convertLocalDateTime(value, ZoneId.of("Asia/Shanghai"), ZoneId.of("Africa/Sao_Tome")) .format(formatter)); } } /** * LocalDateTime反序列化 * */ public static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { private DateTimeFormatter formatter; public CustomLocalDateTimeDeserializer(DateTimeFormatter formatter) { super(); this.formatter = formatter; } @Override public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException, JacksonException { return convertLocalDateTime(LocalDateTime.parse(parser.getText(), formatter), ZoneId.of("Africa/Sao_Tome"), ZoneId.of("Asia/Shanghai")); } } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> { builder.serializerByType(LocalDateTime.class, new CustomLocalDateTimeSerializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat()))); builder.deserializerByType(LocalDateTime.class, new CustomLocalDateTimeDeserializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat()))); }; } }
上面範例程式碼設定使用者時區ZoneId=Africa/Sao_Tome,並且自訂處理了LocalDateTime反序列化器,當使用ResquestBody註解時,物件中的LocalDateTime屬性值也會轉換成UTC 8時區,不用再額外處理,可直接儲存到資料庫。
四、SpringBoot接收時間參數統一處理時區
除了上面所說透過ResquestBody註解來接收參數外,還可能透過Get或Post參數來接收LocalDateTime對象,這時候我們就要自訂一個Converter來處理String轉換到LocalDateTime,同時把使用者提交的屬於使用者時區的物件轉換成UTC 8時區物件。
@Configuration public class WebMvcConfiguration implements WebMvcConfigurer { @Autowired private WebMvcProperties webMvcProperties; @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new Converter<String, LocalDateTime>() { private LocalDateTime convertLocalDateTime(LocalDateTime localDateTime, ZoneId originZoneId, ZoneId targetZoneId) { return localDateTime.atZone(originZoneId).withZoneSameInstant(targetZoneId).toLocalDateTime(); } @Override public LocalDateTime convert(String source) { return convertLocalDateTime( LocalDateTime.parse(source, DateTimeFormatter.ofPattern(webMvcProperties.getFormat().getDateTime())), ZoneId.of("Africa/Sao_Tome"), ZoneId.of("Asia/Shanghai")); } }); }}
以上是SpringBoot怎麼根據使用者係統時區動態展示時間的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生產性。 1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允許CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java實現“一次編寫,到處運行”通過編譯成字節碼並在Java虛擬機(JVM)上運行。 1)編寫Java代碼並編譯成字節碼。 2)字節碼在任何安裝了JVM的平台上運行。 3)使用Java原生接口(JNI)處理平台特定功能。儘管存在挑戰,如JVM一致性和平台特定庫的使用,但WORA大大提高了開發效率和部署靈活性。

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1
強大的PHP整合開發環境

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver Mac版
視覺化網頁開發工具