java时间时区选择,在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;

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).

How can I do it? I am struggling for over a week with Java calendar and with no success!

解决方案

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.

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.

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值