从当地获得GMT的时间

时间:2014-12-24 11:21:09

标签: 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]

根据法国而不是印度(目前我在印度),它没有显示时间。格林威治标准时间与印度相同,而不是法国。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您无法从区域设置派生时区。无论用户实际位于何处,用户都可以为其浏览器选择区域设置。此外,许多语言环境跨越许多时区。如果您想知道用户的时区,您可以通过查找IP地址的位置来尝试猜测,或者您可以提供允许用户告诉您它们的位置。