为如何比较 Java 中不同时区的时间而苦恼?

Struggling with how to compare hours with different time zones in Java?(为如何比较 Java 中不同时区的时间而苦恼?)

本文介绍了为如何比较 Java 中不同时区的时间而苦恼?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有 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 中不同时区的时间而苦恼?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为如何比较 Java 中不同时区的时间而苦恼?

基础教程推荐