我需要一些帮助,将给定的本地日期时间值(或util date)转换为以下格式中的一种(ASIACOLOMBO)时区。以下是格式(来自one-signal API)。
"Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)"
"2015年9月24日下午2点00分(UTC-07-00)"
"2015-09-24 14:00:00 GMT-0700"
"2015年9月24日 14:00:00 GMT-0700"
"Thu Sep 24 2015 14:00:00 GMT-0700(太平洋夏令时)"
谢谢。
ZonedDateTime
将一个日期、时间和区间实例化为一个 ZonedDateTime
对象。
LocalDate ld = LocalDate.of( 2015 , Month.SEPTEMBER , 24 ) ;
LocalTime lt = LocalTime.of( 14 , 0 ) ;
ZoneId z = ZoneId.of( "Asia/Colombo" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
如果给定一个 java.util.Date
对象,转换为一个 Instant
.
Instant instant = myJavaUtilDate.toInstant() ;
应用一个区域从UTC移动。
ZoneId z = ZoneId.of( "Asia/Colombo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
要生成所需格式的文本,请使用 DateTimeFormatter
类。这个问题在Stack Overflow上已经解决了很多很多次。所以搜索该类名来了解更多。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss OOOO" ) ;
String output = zdt.format( f ) ;
2015-09-24 14:00:00 GMT 05:30
你展示的那些格式都是 糟糕 的选择。当将日期-时间值交换为文本时,请使用标准的 ISO 8601 的格式。标准格式的设计是为了便于机器解析,也便于不同文化背景的人阅读。
该 java.time 类在解析生成字符串时默认使用ISO 8601格式。
java.time类是在1.8中引入的,它允许更灵活和简洁的代码。
Instant now = Instant.now();
ZonedDateTime dateTime = now.atZone(ZoneId.of("Asia/Colombo"));
DateTimeFormatter format = DateTimeFormatter.ofPattern("E M d u HH:mm:ss OOOO (z)");
// Using a format to convert at Temporal to a string
String formattedDate = format.format(dateTime);
// Using a format to convert a string to a Instant
Instant parsedDate = Instant.from(format.parse(formattedDate));
你可以使用 DateTimeFormatter.ofPattern
或DateTimeFormatter中定义的许多常量之一。的 模式 符合你的第一个例子。
这些类还没有被废弃,我发现对于简单的情况来说,比现代方法更直接。
java.text.SimpleDateFormat; 它可以处理字符串和java.util.Date对象的转入和转出。
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z (z)");
format.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));
// Note that the current date and time will be used when instantiating a new Date object.
String formattedDate = format.format(new Date());
try {
Date parsedDate = format.parse(formattedDate);
} catch (ParseException exception) {
// Handle malformed date
}
你只需要 成型 为您想使用的任何格式。
EEE MMM dd yyyy HH:mm:ss Z (z) = Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)