在Java中如何与不同的时区比较小时? [英] Struggling with how to compare hours with different time zones in Java?

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

问题描述

我在数据库中有两个表示公司工作时间的日期对象。

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.util .Date 类是一个容器,自1970年1月1日00:00:00 UTC起,保存若干毫秒。注意, Date 类不知道关于时区的任何。

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.

日期不适合持有一个没有日期的小时数(例如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);

如果你还想花几分钟:

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中如何与不同的时区比较小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆