【问题标题】:to get time in GMT from locale从语言环境获取 GMT 时间
【发布时间】:2014-12-24 21:11:37
【问题描述】:

我面临一个问题。 假设用户在 2014 年 12 月 24 日上午 01:00 从中国登录我的网站,所以我存储了他的登录时间。现在,如果他再次从法国登录,那么我需要根据格林威治标准时间 2014 年 12 月 23 日 17:00 显示他按照法国时区的最后登录时间。我有他登录的用户的语言环境信息。 这是我的代码:

String lastLoggedIndatetime = "2014-11-23 04:01" ; //time of last logged in from China; 
Locale locale = Locale.FRANCE; //suppose this i am getting as args from Http request

SimpleDateFormat loggedInDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm");
Calendar c = Calendar.getInstance(locale);
TimeZone loggedInTimeZone = c.getTimeZone();
System.out.println("Time Zone is "+ c.getTimeZone().getDisplayName());

SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm");
TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTimeZone);
try {
    String lastLoggedIndatetimeAsPerFrance = loggedInDateFormat.format(new SimpleDateFormat("yyyy-mm-dd hh:mm").parse(lastLoggedIndatetime.trim()));
    String gmtDateTime= gmtFormat.format(new SimpleDateFormat("yyyy-mm-dd hh:mm").parse(lastLoggedIndatetimeAsPerFrance.trim()));
    System.out.println("last logged in Date as per France is "+ lastLoggedIndatetimeAsPerFrance + "  TimeZone is "+loggedInTimeZone);
    System.out.println("GMT Date is "+ gmtDateTime + "  TimeZone is "+ gmtTimeZone); 
    //formattedDate.append(gmtDateTime)
    //.append(" - "); //" - " is delimiter for date
} catch (ParseException ex) {
    Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
}

输出是:

Time Zone is India Standard Time
last logged in Date as per France is 2014-01-23 04:01  TimeZone is sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]

GMT Date is 2014-31-22 10:31  TimeZone is sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]

它显示的时间不是法国而是印度(目前我在印度)。 GMT 也是印度,而不是法国。

【问题讨论】:

  • 你没有将locale信息传递给SimpleDateFormat,你能不能尝试传递locale
  • 仍然无法正常工作,得到相同的 o/p :: 时区是印度标准时间

标签: java datetime locale


【解决方案1】:

在进行任何操作之前,您需要在Calendar 实例中设置TimeZone

Calendar c = Calendar.getInstance(locale);
c.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); //like this
TimeZone loggedInTimeZone = c.getTimeZone();

【讨论】:

    【解决方案2】:

    您不能从区域设置中派生时区。无论用户实际在哪里,用户都可以为其浏览器选择区域设置。此外,许多语言环境跨越许多时区。如果您想知道用户所在的时区,您可以尝试通过查找 ip 地址的位置来猜测,或者您可以允许用户告诉您他们在哪里。

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 2016-07-11
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      相关资源
      最近更新 更多