問題描述
我在數據庫中有 2 個代表公司工作時間的日期對象.
I have 2 date object in the database that represent the company's working hours.
我只需要時間,但因為我必須保存日期.它看起來像這樣:
I only need the hours but since I have to save date. it appears like this:
Date companyWorkStartHour;
Date companyWorkEndHour;
開始時間:12-12-2001-13:00:00結束時間:12-12-2001-18:00:00
start hours: 12-12-2001-13:00:00 finish hours: 12-12-2001-18:00:00
我有公司和用戶的時區.(我的服務器可能在另一個時區).
I have the timezone of the company and of the user. (my server may be in another timezone).
TimeZone userTimeZone;
TimeZone companyTimeZone;
我需要檢查用戶的當前時間(考慮到他的時區)是否在公司工作時間內(考慮到公司的時區).
I need to check if the user's current time (considering his timezone) is within the company working hours (considering the company's time zone).
我該怎么做?我在 Java 日歷上苦苦掙扎了一個多星期,但沒有成功!
How can I do it? I am struggling for over a week with Java calendar and with no success!
推薦答案
java.util.Date
類是一個容器,它保存了自 1970 年 1 月 1 日 00:00:00 以來的毫秒數世界標準時間.請注意,類 Date
對時區一無所知.如果您需要使用時區,請使用類 Calendar
.(edit 2017 年 1 月 19 日:如果您使用的是 Java 8,請使用包 java.time
中的新日期和時間 API).
The java.util.Date
class is a container that holds a number of milliseconds since 1 January 1970, 00:00:00 UTC. Note that class Date
doesn't know anyting about timezones. Use class Calendar
if you need to work with timezones. (edit 19-Jan-2017: if you are using Java 8, use the new date and time API in package java.time
).
Class Date
并不適合保存沒有日期的小時數(例如 13:00 或 18:00).它根本不是為了那個目的而設計的,所以如果你嘗試像那樣使用它,就像你正在做的那樣,你會遇到很多問題,你的解決方案也不會優雅.
Class Date
is not really suited for holding an hour number (for example 13:00 or 18:00) without a date. It's simply not made for that purpose, so if you try to use it like that, as you seem to be doing, you'll run into a number of problems and your solution won't be elegant.
如果您忘記使用類 Date
來存儲工作時間而只使用整數,這會簡單得多:
If you forget about using class Date
to store the working hours and just use integers, this will be much simpler:
Date userDate = ...;
TimeZone userTimeZone = ...;
int companyWorkStartHour = 13;
int companyWorkEndHour = 18;
Calendar cal = Calendar.getInstance();
cal.setTime(userDate);
cal.setTimeZone(userTimeZone);
int hour = cal.get(Calendar.HOUR_OF_DAY);
boolean withinCompanyHours = (hour >= companyWorkStartHour && hour < companyWorkEndHour);
如果您還想考慮幾分鐘(而不僅僅是幾小時),您可以這樣做:
If you also want to take minutes (not just hours) into account, you could do something like this:
int companyWorkStart = 1300;
int companyWorkEnd = 1830;
int time = cal.get(Calendar.HOUR_OF_DAY) * 100 + cal.get(Calendar.MINUTE);
boolean withinCompanyHours = (time >= companyWorkStart && time < companyWorkEnd);
這篇關于為如何比較 Java 中不同時區的時間而苦惱?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!