java - 从语言环境获取 GMT 时间

标签 java datetime locale

我面临一个问题。 假设用户于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 是印度的格林威治标准时间,而不是法国的格林威治标准时间。

最佳答案

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

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

关于java - 从语言环境获取 GMT 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27636101/

相关文章:

javascript - 是什么阻止 HtmlUnit 加载 PSN 商店页面?

java - Gradle 使用 2 个不同的 JDK

C# 如何控制 MySql Connector 返回的日期时间格式

Android - 方向更改时强制重置区域设置

java - 两个类之间可能的递归 Java 泛型

java - 如何在elasticsearch中检索嵌套文档和数组值

c# - 检查日期 x 是否早于某些天数

date - Knockout - 如何仅绑定(bind)日期

python - 使用区域设置打印以色列货币

java - MissingResourceException - 找不到基本名称的包