时间戳1522899000000格式(Ionic/AngularJS)及Java转换方法问询
First, let’s clarify the core issue here: 1522899000000 is a Unix timestamp in milliseconds (count of milliseconds since the Unix epoch: January 1, 1970, 00:00:00 UTC).
Question 1: Format Type & Ionic/AngularJS Relevance
This is a standard millisecond-precision Unix timestamp, and yes, it’s commonly used in both Ionic and AngularJS. Here’s why:
- JavaScript (which both frameworks rely on) uses
Dateobjects that natively accept millisecond timestamps as input. When these frameworks handle dates from APIs, they often pass around this millisecond format because it’s easy to serialize/deserialize and works seamlessly with JS’s date handling.
To use this timestamp in Java:
You have two main approaches depending on your Java version:
Modern Java (8+): Use the java.time API (Recommended)
The java.time package is the preferred way to handle dates now—it’s immutable, thread-safe, and avoids the pitfalls of legacy classes.
import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; // Convert the millisecond timestamp to an Instant (UTC-based) Instant instant = Instant.ofEpochMilli(1522899000000L); // If you need a timezone-specific datetime (e.g., UTC or your local time) LocalDateTime utcDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("UTC")); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); System.out.println(utcDateTime); // Output: 2018-04-05T09:30:00
Legacy Java (Pre-8): Use Date or Calendar
If you’re stuck with older Java versions, you can use the legacy date classes:
import java.util.Date; import java.util.Calendar; // Using Date Date date = new Date(1522899000000L); System.out.println(date); // Output depends on your default timezone, e.g., Wed Apr 05 05:30:00 EDT 2018 // Using Calendar Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(1522899000000L); // Access individual fields like year, month, day int year = calendar.get(Calendar.YEAR); // 2018
Question 2: Why Conversion Gave 1912 & Fixing It
The issue here is almost certainly that you treated the millisecond timestamp as a second-based Unix timestamp—and likely ran into integer overflow if you used a 32-bit integer type. Let’s break it down:
- The correct second-based timestamp for 2018-04-05 is
1522899000(divide the millisecond value by 1000). - The value
1522899000000is way larger than the maximum value of a 32-bit signed integer (2147483647). When you try to use it as a second-based timestamp in a 32-bit context, it overflows to a negative number, which translates to a date before the Unix epoch (1970), hence the incorrect 1912 result.
To convert it to a Java datetime type, use the exact same methods as in Question 1 above. The key is to use millisecond-specific conversion methods (ofEpochMilli for Instant, setTimeInMillis for Calendar, or the Date constructor that takes a long).
内容的提问来源于stack exchange,提问作者Junior Dev

