主頁 > 區塊鏈 > 考慮到夏季時間的變化,這段代碼是否適合用Java計算時間?

考慮到夏季時間的變化,這段代碼是否適合用Java計算時間?

2021-10-21 07:49:56 區塊鏈

有人可以幫我解決這個困惑嗎?我需要顯示每個工人的總作業時間。有不同的作業班次。在這種情況下,最復雜的是當人們從一天的 21:00 作業到第二天的 7:00 時的黎明轉變,考慮到日偏移,即在 10 月 31 日,瑞士有時間變化。我打算只在國內應用這個邏輯。以下代碼是否是這種情況的可靠解決方案?我曾嘗試了解 java.time 和針對此特定問題的許多帖子,但它們都變得更加混亂。

public String saveWorkTime(@Valid @ModelAttribute("workCalc") WorkCalculator workCalculator,
                               BindingResult bindingResult, ModelMap modelMap) throws ParseException {

        (...)

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        Date startDT = sdf.parse(workCalculator.getStartDate()   " "   workCalculator.getStartTime());
        Date endDT = sdf.parse(workCalculator.getEndDate()   " "   workCalculator.getEndTime());

        long timeDiffMilli = endDT.getTime() - startDT.getTime();
        long timeDiffMin = TimeUnit.MILLISECONDS.toMinutes(timeDiffMilli) % 60;
        long timeDiffH = TimeUnit.MILLISECONDS.toHours(timeDiffMilli) % 24;

        workCalculator.setTotalWorkH(timeDiffH);
        workCalculator.setTotalWorkMin(timeDiffMin);

        workCalculatorService.save(workCalculator);
        return "redirect:/index";
}

我的物體模型如下所示:

 (...)

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "id")
 private Integer id;

 @Column(name = "start_date")
 private String startDate;

 @Column(name = "end_date")
 private String endDate;

 @Column(name = "total_work_h")
 private long totalWorkH;

 @Column(name = "total_work_min")
 private long totalWorkMin;

 @Column(name = "end_time")
 private String endTime;

 @Column(name = "start_time")
 private String startTime;

 (...)

我的資料庫架構看起來像:

(...)

CREATE TABLE `work_calc` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `start_date` varchar(30) DEFAULT NULL,
    `end_date` varchar(30) DEFAULT NULL,
    `start_time` varchar(20) DEFAULT NULL,
    `end_time` varchar(20) DEFAULT NULL,
    `total_work_h` int(10) DEFAULT NULL,
    `total_work_min` int(10) DEFAULT NULL,

    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1; 

考慮到夏季時間的變化,這段代碼是否適合用 Java 計算時間?

提前感謝大家的努力和時間。

uj5u.com熱心網友回復:

時間

這很簡單。如果你只是允許它存在。我建議您對所有日期和時間作業使用 java.time,現代 Java 日期和時間 API。

// This should be your entity class
public class Work {
    
    private static final DateTimeFormatter FORMATTER
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ROOT);
    
    private OffsetDateTime start;
    private OffsetDateTime end;
    
    public Work(OffsetDateTime start, OffsetDateTime end) {
        this.start = start;
        this.end = end;
    }

    public Duration getTotalWorkTime() {
        return Duration.between(start, end);
    }

    @Override
    public String toString() {
        return start.format(FORMATTER)   " - "   end.format(FORMATTER);
    }
    
}

讓我們試試看。為了構造一些Work物件,我撰寫了以下輔助方法。它接受日期和時間的字串。

/** Switzerland time */
private static final ZoneId ZONE = ZoneId.of("Europe/Zurich");

private static Work buildWork(String startDate, String startTime,
        String endDate, String endTime) {
    ZonedDateTime start = ZonedDateTime.of(
            LocalDate.parse(startDate), LocalTime.parse(startTime), ZONE);
    ZonedDateTime end = ZonedDateTime.of(
            LocalDate.parse(endDate), LocalTime.parse(endTime), ZONE);
    
    if (start.isAfter(end)) {
        throw new IllegalArgumentException("Start must not be after end");
    }
    
    return new Work(start.toOffsetDateTime(), end.toOffsetDateTime());
}

示范:

    Work[] exampleEntities = {
            buildWork("2021-10-13", "07:00", "2021-10-14", "17:45"),
            buildWork("2021-10-15", "07:00", "2021-10-15", "21:00"),
            buildWork("2021-10-30", "21:00", "2021-10-31", "07:00")
    };

    for (Work work : exampleEntities) {
        Duration totalWork = work.getTotalWorkTime();
        System.out.format("%s: %-8s or - hours - minutes%n", work,
                totalWork, totalWork.toHours(), totalWork.toMinutesPart());
    }

輸出:

2021-10-13 07:00 - 2021-10-14 17:45: PT34H45M or 34 hours 45 minutes
2021-10-15 07:00 - 2021-10-15 21:00: PT14H    or 14 hours  0 minutes
2021-10-30 21:00 - 2021-10-31 07:00: PT11H    or 11 hours  0 minutes

In a normal night we would expect the time from 21:00 to 7:00 to be 10 hours. You can see in the above output that in the night between October 30 and 31, where Europe turns its clocks back after summer time (DST), it’s 11 hours. Edit: If one is in doubt, here’s a way to see it: The worker first works from 21 to 3 = 6 hours. Then the clocks are turned back to 2. The worker then continues working from 2 to 7 = 5 hours. So the total time worked i 6 5 hours = 11 hours. So the code calculates the actual time elapsed (not the difference between the clock hours).

Further points I wanted to make

  1. Use proper date-time objects for storing date and time. You don’t store numbers and Boolean values in strings (I sure hope), you also should not store dates and times in strings. I had really wanted to use ZonedDateTime for a date and time with a time zone (like Europe/Zurich), but many SQL databases cannot store the value of a ZonedDateTime with a real time zone, so we may have to use OffsetDateTime as in the code above. An OffsetDateTime fits nicely into a timestamp with time zone column of common SQL databases, though variations between vendors are great. For an amount of time use the Duration class in Java (not separate numbers).
  2. Don’t store redundant information in your entity. The risk of some database update causing undetected data inconsistency is too great. Total work time can be calculated from start and end, so we simply calculate them on demand (which probably isn’t that often, but you know better).
  3. As MadProgrammer said in a comment, leave to the standard library methods to perform date and time math. It’s often more complicated than you think, so don’t do it by hand as in your own code.

Was your code reliable?

Giving just a partial answer to your question as asked. There isn’t much reliable about the old date and time classes from Java 1.0 and 1.1. Even if you get code to work with them, it will often be needlessly complicated code, and the risk of some fellow programmer introducing a bug later should not be overlooked.

I didn’t test your code with data from the nights of fall back (for example 30–31 October 2021) and spring forward (expected 26–27 March 2022). You can do that yourself.

You have got a very long work shift from 2021-10-13 07:00 to 2021-10-14 17:45. It may be an error in the data, but work time should be calculated correctly, which will also help the user notice if it is indeed an error. The correct duration is 34 hours 45 minutes. It seems from your screen shot that your code has calculated it as just 10 hours 45 minutes.

Link

Oracle tutorial: Date Time explaining how to use java.time.

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/327969.html

標籤:爪哇 弹簧靴 日期 时间 日期时间偏移

上一篇:Pandas:將匯率查詢乘以另一個資料幀中的相同日期后,按每日金額求和并匯總

下一篇:為什么setDate在傳遞字串值時會給出奇怪的答案?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • JAVA使用 web3j 進行token轉賬

    最近新學習了下區塊鏈這方面的知識,所學不多,給大家分享下。 # 1. 關于web3j web3j是一個高度模塊化,反應性,型別安全的Java和Android庫,用于與智能合約配合并與以太坊網路上的客戶端(節點)集成。 # 2. 準備作業 jdk版本1.8 引入maven <dependency> < ......

    uj5u.com 2020-09-10 03:03:06 more
  • 以太坊智能合約開發框架Truffle

    前言 部署智能合約有多種方式,命令列的瀏覽器的渠道都有,但往往跟我們程式員的風格不太相符,因為我們習慣了在IDE里寫了代碼然后打包運行看效果。 雖然現在IDE中已經存在了Solidity插件,可以撰寫智能合約,但是部署智能合約卻要另走他路,沒辦法進行一個快捷的部署與測驗。 如果團隊管理的區塊節點多、 ......

    uj5u.com 2020-09-10 03:03:12 more
  • 谷歌二次驗證碼成為區塊鏈專用安全碼,你怎么看?

    前言 谷歌身份驗證器,前些年大家都比較陌生,但隨著國內互聯網安全的加強,它越來越多地出現在大家的視野中。 比較廣泛接觸的人群是國際3A游戲愛好者,游戲盜號現象嚴重+國外賬號安全應用廣泛,這類游戲一般都會要求用戶系結名為“兩步驗證”、“雙重驗證”等,平臺一般都推薦用谷歌身份驗證器。 后來區塊鏈業務風靡 ......

    uj5u.com 2020-09-10 03:03:17 more
  • 密碼學DAY1

    目錄 ##1.1 密碼學基本概念 密碼在我們的生活中有著重要的作用,那么密碼究竟來自何方,為何會產生呢? 密碼學是網路安全、資訊安全、區塊鏈等產品的基礎,常見的非對稱加密、對稱加密、散列函式等,都屬于密碼學范疇。 密碼學有數千年的歷史,從最開始的替換法到如今的非對稱加密演算法,經歷了古典密碼學,近代密 ......

    uj5u.com 2020-09-10 03:03:50 more
  • 密碼學DAY1_02

    目錄 ##1.1 ASCII編碼 ASCII(American Standard Code for Information Interchange,美國資訊交換標準代碼)是基于拉丁字母的一套電腦編碼系統,主要用于顯示現代英語和其他西歐語言。它是現今最通用的單位元組編碼系統,并等同于國際標準ISO/IE ......

    uj5u.com 2020-09-10 03:04:50 more
  • 密碼學DAY2

    ##1.1 加密模式 加密模式:https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html ECB ECB : Electronic codebook, 電子密碼本. 需要加密的訊息按照塊密碼的塊大小被分為數個塊,并對每個塊進 ......

    uj5u.com 2020-09-10 03:05:42 more
  • NTP時鐘服務器的特點(京準電子)

    NTP時鐘服務器的特點(京準電子) NTP時鐘服務器的特點(京準電子) 京準電子官V——ahjzsz 首先對時間同步進行了背景介紹,然后討論了不同的時間同步網路技術,最后指出了建立全球或區域時間同步網存在的問題。 一、概 述 在通信領域,“同步”概念是指頻率的同步,即網路各個節點的時鐘頻率和相位同步 ......

    uj5u.com 2020-09-10 03:05:47 more
  • 標準化考場時鐘同步系統推進智能化校園建設

    標準化考場時鐘同步系統推進智能化校園建設 標準化考場時鐘同步系統推進智能化校園建設 安徽京準電子科技官微——ahjzsz 一、背景概述隨著教育事業的快速發展,學校建設如雨后春筍,隨之而來的學校教育、管理、安全方面的問題成了學校管理人員面臨的最大的挑戰,這些問題同時也是學生家長所擔心的。為了讓學生有更 ......

    uj5u.com 2020-09-10 03:05:51 more
  • 位元幣入門

    引言 位元幣基本結構 位元幣基礎知識 1)哈希演算法 2)非對稱加密技術 3)數字簽名 4)MerkleTree 5)哪有位元幣,有的是UTXO 6)位元幣挖礦與共識 7)區塊驗證(共識) 總結 引言 上一篇我們已經知道了什么是區塊鏈,此篇說一下區塊鏈的第一個應用——位元幣。其實先有位元幣,后有的區塊 ......

    uj5u.com 2020-09-10 03:06:15 more
  • 北斗對時服務器(北斗對時設備)電力系統應用

    北斗對時服務器(北斗對時設備)電力系統應用 北斗對時服務器(北斗對時設備)電力系統應用 京準電子科技官微(ahjzsz) 中國北斗衛星導航系統(英文名稱:BeiDou Navigation Satellite System,簡稱BDS),因為是目前世界范圍內唯一可以大面積提供免費定位服務的系統,所以 ......

    uj5u.com 2020-09-10 03:06:20 more
最新发布
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:46:47 more
  • Hyperledger Fabric 使用 CouchDB 和復雜智能合約開發

    在上個實驗中,我們已經實作了簡單智能合約實作及客戶端開發,但該實驗中智能合約只有基礎的增刪改查功能,且其中的資料管理功能與傳統 MySQL 比相差甚遠。本文將在前面實驗的基礎上,將 Hyperledger Fabric 的默認資料庫支持 LevelDB 改為 CouchDB 模式,以實作更復雜的資料... ......

    uj5u.com 2023-04-16 07:28:31 more
  • .NET Core 波場鏈離線簽名、廣播交易(發送 TRX和USDT)筆記

    Get Started NuGet You can run the following command to install the Tron.Wallet.Net in your project. PM> Install-Package Tron.Wallet.Net 配置 public reco ......

    uj5u.com 2023-04-14 08:08:00 more
  • DKP 黑客分析——不正確的代幣對比率計算

    概述: 2023 年 2 月 8 日,針對 DKP 協議的閃電貸攻擊導致該協議的用戶損失了 8 萬美元,因為 execute() 函式取決于 USDT-DKP 對中兩種代幣的余額比率。 智能合約黑客概述: 攻擊者的交易:0x0c850f,0x2d31 攻擊者地址:0xF38 利用合同:0xf34ad ......

    uj5u.com 2023-04-07 07:46:09 more
  • Defi開發簡介

    Defi開發簡介 介紹 Defi是去中心化金融的縮寫, 是一項旨在利用區塊鏈技術和智能合約創建更加開放,可訪問和透明的金融體系的運動. 這與傳統金融形成鮮明對比,傳統金融通常由少數大型銀行和金融機構控制 在Defi的世界里,用戶可以直接從他們的電腦或移動設備上訪問廣泛的金融服務,而不需要像銀行或者信 ......

    uj5u.com 2023-04-05 08:01:34 more
  • solidity簡單的ERC20代幣實作

    // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "hardhat/console.sol"; //ERC20 同質化代幣,每個代幣的本質或性質都是相同 //ETH 是原生代幣,它不是ERC20代幣, ......

    uj5u.com 2023-03-21 07:56:29 more
  • solidity 參考型別修飾符memory、calldata與storage 常量修飾符C

    在solidity語言中 參考型別修飾符(參考型別為存盤空間不固定的數值型別) memory、calldata與storage,它們只能修飾參考型別變數,比如字串、陣列、位元組等... memory 適用于方法傳參、返參或在方法體內使用,使用完就會清除掉,釋放記憶體 calldata 僅適用于方法傳參 ......

    uj5u.com 2023-03-08 07:57:54 more
  • solidity注解標簽

    在solidity語言中 注釋符為// 注解符為/* 內容*/ 或者 是 ///內容 注解中含有這幾個標簽給予我們使用 @title 一個應該描述合約/介面的標題 contract, library, interface @author 作者的名字 contract, library, interf ......

    uj5u.com 2023-03-08 07:57:49 more
  • 評價指標:相似度、GAS消耗

    【代碼注釋自動生成方法綜述】 這些評測指標主要來自機器翻譯和文本總結等研究領域,可以評估候選文本(即基于代碼注釋自動方法而生成)和參考文本(即基于手工方式而生成)的相似度. BLEU指標^[^?88^^?^]^:其全稱是bilingual evaluation understudy.該指標是最早用于 ......

    uj5u.com 2023-02-23 07:27:39 more
  • 基于NOSTR協議的“公有制”版本的Twitter,去中心化社交軟體Damus

    最近,一個幽靈,Web3的幽靈,在網路游蕩,它叫Damus,這玩意詮釋了什么叫做病毒式營銷,滑稽的是,一個Web3產品卻在Web2的產品鏈上瘋狂傳銷,各方大佬紛紛為其背書,到底發生了什么?Damus的葫蘆里,賣的是什么藥? 注冊和簡單實用 很少有什么產品在用戶注冊環節會有什么噱頭,但Damus確實出 ......

    uj5u.com 2023-02-05 06:48:39 more