【问题标题】:Get server date time with different timezone获取具有不同时区的服务器日期时间
【发布时间】:2013-07-13 15:25:33
【问题描述】:

我想向客户端显示与服务器日期时间相同的服务器日期时间。此日期用于实现一些按计划进行的功能。我执行以下步骤:

  • 从服务器获取初始日期时间和刚刚计算的时间 date.getTime() 不同。

  • 将时间差异添加到客户端日期时间

  • 使用 GWT 的 Timer 更新客户端时间

当服务器时区和客户端时区相同时,它工作正常。但它给了我不同时区的错误计算。

举例: 如果我的客户时间是印度时区

((UTC+05:30)钦奈、加尔各答、孟买、新德里)

和 服务器时区是

((UTC-08:00) 太平洋时间(美国和加拿大))

所以它计算错误的服务器日期。

如何在不频繁发出服务器请求的情况下显示服务器和客户端不同时区的当前服务器时间?

注意:解决方案应该是通用时区。

编辑:

我使用了 RPC 机制并将 new Date().getTime() 从服务器返回到客户端。 而在成功方法中,客户端代码:

final String serverDate;
            final DateTimeFormat fmt = DateTimeFormat.getFormat(dateFormat);
            if(dateFormat!=null){
                serverDate = fmt.format(result.getServerDate());
            }else{
                serverDate = result.getServerDate().toString();
            }
            setDateTime(serverDate,widget);
            final long dateDiff = result.getServerDate().getTime()-new Date().getTime();
            Timer timer = new Timer() {
                @Override
                public void run() {
                    long currenrDate=new Date().getTime()+dateDiff;
                    Date date=new Date(currenrDate);
                    String serverDate = fmt.format(date);
                    setDateTime(serverDate,widget);
                    WorkFlowSessionFactory.putValue(WorkFlowSesisonKey.SERVER_DATE_TIME,date);  

                }
            };
            timer.scheduleRepeating(10000);

【问题讨论】:

  • 请编辑您的问题以提供更多详细信息。你试过什么?客户端和服务器上都是纯 Java 吗?你如何在它们之间传递价值?当您说“客户端”时,您是指浏览器中的客户端 JavaScript - 这是完全不同的。请准确。谢谢。
  • Server and client means two different machines 如果服务器机器有不同的时区并且那个时间我需要在客户端机器上显示。战争在 gwt 技术中展开。它是纯java脚本。我编辑我的问题。

标签: java datetime


【解决方案1】:

你尝试过这样的事情吗?

    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date=new Date();
    System.out.println(f.format(date));   // current UTC time

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.HOUR_OF_DAY, 5);
    cal.add(Calendar.MINUTE, 30);
    System.out.println(f.format(cal.getTime()));// current client side time in UTC

    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(date);
    cal2.add(Calendar.HOUR_OF_DAY, -8);
    cal2.add(Calendar.MINUTE, 00);
    System.out.println(f.format(cal2.getTime()));// current server side time in UTC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    相关资源
    最近更新 更多