如何将Java时间戳字符串转换为Java时间戳对象?以及如何解析无符号时区偏移的时间字符串为java.time.Instant?
Instant Let's tackle both of your questions, with a deep dive into the second one since that's the tricky part you're stuck on.
1. Converting a Timestamp String to a Java Timestamp Object
First, note that "timestamp string" can refer to two common types—here's how to handle both:
- Epoch timestamp string (e.g.,
"1609459200000"for milliseconds since the Unix epoch):
Parse it to a numeric type and useInstant's factory methods directly:String epochStr = "1609459200000"; Instant instant = Instant.ofEpochMilli(Long.parseLong(epochStr)); // Use Instant.ofEpochSecond(...) if the string represents seconds since epoch - Human-readable formatted timestamp string (like your example):
You'll need aDateTimeFormatterto parse it, which leads straight to your core problem.
2. Parsing "2021010112:12:12.10:00" to Instant
The issue here is that the timezone offset (10:00) lacks a required sign—Java's default DateTimeFormatter expects offsets to include + or - per ISO-8601 standards. Since you know this offset represents UTC+10:00, here are two reliable solutions:
Solution 1: Preprocess the String to Add the Sign
This is the simplest fix if you're confident all unsigned offsets are positive:
String input = "2021010112:12:12.10:00"; // Insert a "+" right after the final dot where the offset begins int lastDotIndex = input.lastIndexOf('.'); String adjustedInput = new StringBuilder(input) .insert(lastDotIndex + 1, "+") .toString(); // Use a standard formatter for the adjusted string DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHH:mm:ss.XXX"); ZonedDateTime zonedDateTime = ZonedDateTime.parse(adjustedInput, formatter); Instant instant = zonedDateTime.toInstant();
Solution 2: Build a Custom Formatter for Unsigned Offsets
If you need to support both unsigned (positive) and signed offsets (e.g., -05:00), use DateTimeFormatterBuilder to create a formatter that treats unsigned offsets as positive values:
String input = "2021010112:12:12.10:00"; DateTimeFormatter customFormatter = new DateTimeFormatterBuilder() // Append the main date-time pattern .appendPattern("yyyyMMddHH:mm:ss.") // Define an offset parser that accepts unsigned values (defaults to positive) .appendOffset("HH:mm", "+00:00") .toFormatter(); // Parse directly to ZonedDateTime, then convert to Instant ZonedDateTime zonedDateTime = ZonedDateTime.parse(input, customFormatter); Instant instant = zonedDateTime.toInstant();
Verify the Result
Both solutions will output the same Instant for your input: 2021-01-01T02:12:12Z (since 12:12:12 UTC+10:00 translates to 02:12:12 UTC).
内容的提问来源于stack exchange,提问作者Kuldeep Singh

