在服务器端java类中读取客户端时区

我有一个客户端程序,它向服务器端程序发送一个时间。
我正在使用Callendar对象将时间值从客户端传递到服务器。
我的客户端程序位于斯里兰卡,服务器位于英国。
当我在客户端发送时间(例如:2011-11-21T12:43:41.352 + 05:30)时,通常是在服务器上转换到英国时间的时间(例如:2011-11-21T07:13:411.352) +00:00)。
我想要做的是我希望得到我在客户端程序中使用时区发送客户端程序的时间。(简单来说,我想在没有TimeZone转换的服务器中读取时间应用于由客户端程序发送。所以在服务器中我想得到的时间是2011-11-21T12:43:41.352 + 05:30而不是2011-11-21T07:13:411.352 + 00:00)。

我可以知道这可以用java来做,如果是的话怎么样?

客户端 :

Calendar cal1 = Calendar.getInstance(); Date indate = new Date(); // this shows as 2011-11-21T12:43:41.352+05:30 searchDateRange_type0.setStart(cal1); cal1.setTime(inDate); 

Serever Side:

 SearchDateRange_type0 serachDaterange= criterion_type.getSearchDateRange(); checkInDate = serachDaterange.getStart().getTime(); //I read this as 2011-11-21T07:13:411.352+00:00 

这里的问题是,当java客户端日历转换日期时,它也设置了它的时区。 如果要清除此状态并且只需要从服务器日历对象获取日期,请在客户端中设置时区时将客户端日历时间分钟和秒设置为0。

恩。 在客户端,

 Date indate = new Date("21-Nov-2011"); Calendar cal1 = Calendar.getInstance(); cal1.setTime(indate); // set the time zone same as server time zone. cal1.setTimeZone(TimeZone.getTimeZone("GMT")); // then clear out the rest in oder to get only the date. cal1.set(Calendar.HOUR, 0); cal1.set(Calendar.MINUTE, 0); cal1.set(Calendar.SECOND, 0); 

所以服务器只获得从客户端传递的相同日期,没有时区或小时。

了解Date值没有时区非常重要。 它只是瞬间代表。 当您调用Date.toString() ,它使用您正在调用它的系统的默认时区。 这就是为什么你会得到你的行为。

因此看起来瞬间本身正在被正确读取 – 但如果您对当地时间感兴趣而不是及时,则有两种选择:

  • 传递时区标识符(例如“欧洲/巴黎”) 以及时刻
  • 传递当地日期或日期/时间,不要试图在一开始就及时处理它

在您的情况下,很难确切知道哪些是最合适的。 我们需要更多地了解应用程序正在做什么,以及如何传输信息。

我建议使用Joda Time而不是内置的日期/时间库 – 它是一个更好的API,可以帮助您区分本地时间和瞬间。

在服务器上设置时间后,您可以拨打电话。
Calendar.setTimezone()
问题是,你必须知道客户的时区。

日期和时间转换为服务器时区格式(例如:CST到IST)

注意 :我的服务器以IST格式运行(默认情况下,JVM采用OS时区)。

  String inputDateString = "2013-10-26 09:36:00"; String timezoneID = "CST"; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); dateFormat.parse(inputDateString+" "+timezoneID); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); formatter.setTimeZone(TimeZone.getTimeZone(dateFormat.getTimeZone().getID())); Date outputDate = formatter.parse(inputDateString); System.out.println(outputDate); 

输出: 2013年10月26日星期六20:06:00 IST 2013