我有一个Date对象,我需要将它转换为登录用户的时区。问题是,在我们的数据库中,时区仅仅表示为GMT加上或减去以小时为单位的偏移量的字符串值。例如,"GMT“或"GMT-5”代表纽约时间或"GMT+5“。
当我只有像"GMT-3“或"GMT+5”这样的字符串时,如何将我的Date对象转换为用户的时间?
提前感谢您的帮助。
发布于 2014-02-09 01:31:55
一个示例应该会有所帮助,但它似乎是一个1个字符的ISO 8601 time zone
String myDate="2001-07-04T12:08:56GMT-3";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'GMT'X");
if (myDate.indexOf("GMT-") >= myDate.length() -1 -4) {
myDate = myDate.replace("-","-0");
}
if (myDate.indexOf("GMT+") >= myDate.length() -1 -4) {
myDate = myDate.replace("+","+0");
}
System.out.println(format.parse(myDate));应该能行得通。
yyyy-MM-dd'T'HH:mm:ss'GMT'X与iso8601 time 兼容可根据您的格式调整日期
发布于 2014-02-09 14:42:39
偏移量≠时区
正如Jon Skeet在评论中所说,时区不仅仅是UTC/GMT的偏移量。存储偏移小时(和分钟)不是处理数据库/存储中的日期-时间的最佳策略。
Joda-Time
java.util.Date和java.util.Calendar类是出了名的麻烦。避开他们。使用Joda-Time。或者,在Java8中,使用JSR310定义的、受Joda-Time启发但经过重新架构的新java.time.* package。
我们可以创建一个DateTimeZone来表示偏移量,但如上所述,这在逻辑上并不是一个完整的时区。
我们可以将java.util.Date对象直接传递给Joda-Time DateTime构造函数。同时,我们传递了一个DateTimeZone对象。要进行相反的转换,请在DateTime对象上调用toDate。
java.util.Date date = new java.util.Date(); // Retrieved from elsewhere. Faked here.
String offsetInput = "GMT-5";
int offsetHours = 0, offsetMinutes = 0;
offsetInput = offsetInput.replace( "GMT", "" ); // Delete 'GMT' characters.
String[] parts = offsetInput.split(":"); // About splitting a string: http://stackoverflow.com/q/3481828/642706
// Handle results of split.
if( parts.length == 0 ) {
// Add some error handling here
}
if ( parts.length >= 1 ) {
offsetHours = Integer.parseInt( parts[0] ); // Retrieve text of first number (zero-based index counting).
}
if ( parts.length >= 2 ) {
offsetMinutes = Integer.parseInt( parts[1] ); // Retrieve text of second number (zero-based index counting).
}
if( parts.length >= 3 ) {
// Add some error handling here
}
DateTimeZone partialTimeZoneWithOnlyOffset = DateTimeZone.forOffsetHoursMinutes( offsetHours, offsetMinutes );
DateTime dateTime = new DateTime( date, partialTimeZoneWithOnlyOffset );转储到控制台…
System.out.println( "date: " + date ); // BEWARE: JVM's default time zone applied in the implicit call to "toString" of a Date. Very misleading.
System.out.println( "partialTimeZoneWithOnlyOffset: " + partialTimeZoneWithOnlyOffset );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime with alternate formatting: " + DateTimeFormat.forStyle( "FF" ).withLocale( Locale.US ).print( dateTime ) );运行…时
date: Sat Feb 08 22:40:57 PST 2014
partialTimeZoneWithOnlyOffset: -05:00
dateTime: 2014-02-09T01:40:57.810-05:00
dateTime with alternate formatting: Sunday, February 9, 2014 1:40:57 AM -05:00https://stackoverflow.com/questions/21648923
复制相似问题