DateTimeFormatter#parse(CharSequence, ParsePosition) https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#parse-java.lang.CharSequence-java.text.ParsePosition-任您支配。
注意NY
不是时区的名称。时区的命名约定是地区/城市 e.g. Europe/Paris
。您可以使用获取时区名称列表ZoneId#getAvailableZoneIds https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#getAvailableZoneIds--.
另外,对于带有序数的月份中的某一天,例如26th,你可以建立一个Map
如下面的代码所示。
Demo:
import java.text.ParsePosition;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String strDateTime ="Jun 26th 2021, 04:30:15 pm NY";
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("[MMMM][MMM] ") // caters for both full name and 3-letter abbv.
.appendText(ChronoField.DAY_OF_MONTH, ordinalMap())
.appendPattern(" u, h:m:s a")
.toFormatter(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.from(dtf.parse(strDateTime, new ParsePosition(0)));
ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/New_York"));
System.out.println(zdt);
}
static Map<Long, String> ordinalMap() {
String[] suffix = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
Map<Long, String> map = new HashMap<>();
for (int i = 1; i <= 31; i++)
map.put((long)i, String.valueOf(i) + suffix[(i > 3 && i < 21) ? 0 : (i % 10)]);
return map;
}
}
Output:
2021-06-26T16:30:15-04:00[America/New_York]
ONLINE DEMO https://ideone.com/Tz4fUT
了解有关现代日期时间 API 的更多信息路线:日期时间 https://docs.oracle.com/javase/tutorial/datetime/index.html.
礼貌:构建逻辑Map
是基于这个优秀的答案 https://stackoverflow.com/a/4011339/10819573.