在我的应用程序中,我需要使用日期、时间和时区对象创建一个公历日历对象。我碰巧拥有字符串/整数格式的所有数据,即: 日、月、年、时、SS、XXX。
E.g. 20 , 03 , 14 , 09 , 30 , PST
我可以使用上述所有参数创建一个日历对象吗??
我尝试使用java Calender
Calendar calendar = new GregorianCalendar(14 , 02 , 20 , 9 , 30 , 00);
calendar.setTimeZone(TimeZone.getTimeZone("PST"));
但它不允许我使用时区并且总是选择我的服务器时区(EDT)。所以我总是以: 2014 年 3 月 20 日星期四 09:30:00 美国东部时间
我真正需要的是:Thu Mar 20 09:30:00 PST 2014
最佳答案
有几个问题。首先,您应该使用 2014 年,而不仅仅是 14 作为 GregorianCalendar 的输入参数。那么SS可能代表分钟,而不是秒?!看看这段注释代码:
// don't use the Calendar class, you surely want the gregorian calendar
GregorianCalendar calendar = new GregorianCalendar(2014, 02, 20, 9, 30, 00); // not 14!!!
// getting time zone via zone name PST which is not unique, it could also stand for
// Pakistan Standard Time, try to use "America/Los_Angeles" (more reliable)
TimeZone tz = TimeZone.getTimeZone("PST");
calendar.setTimeZone(tz);
// output of java.util.Date#toString() depends on local time zone (my case Europe/Berlin => CET)
System.out.println(calendar.getTime()); // Tue Mar 20 18:30:00 CET 14
// PST is 8 hours behind UTC and 9 hours behind CET
System.out.println("PST: " + tz.getRawOffset() / 3600000);
// correct output in PST-zone with your wish format
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(tz);
System.out.println(sdf.format(calendar.getTime()));
我得到的输出:Thu Mar 20 09:30:00 PDT 2014
因此 PDT 而不是 PST(此时在 PST 区域激活夏令时。
System.out.println(tz.inDaylightTime(calendar.getTime())); // true
关于java - 创建包含 YYYY、MM、DD、HH、SS 和时区 (XXX) 的公历日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22516951/