Question
Why does calling SimpleDateFormat.parse().getTime() return a negative value?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("1970-01-01");
long timeInMillis = date.getTime(); // This may return a negative value.
Answer
The SimpleDateFormat class in Java is used to parse strings into Date objects, but it can return negative values when dealing with dates prior to the Unix epoch (January 1, 1970). This behavior can lead to unexpected results when calling the getTime() method on these dates.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("1969-12-31"); // This date is before the Unix epoch.
long timeInMillis = date.getTime(); // This will return a negative value.
System.out.println("Time in milliseconds: " + timeInMillis); // Output: -86400000
}
}
Causes
- The date parsed represents a time before the Unix epoch, which causes getTime() to return a negative value (milliseconds before January 1, 1970).
- The SimpleDateFormat may have an incorrect pattern, resulting in parsing issues and unexpected Date values.
Solutions
- Ensure the date string you are trying to parse is within a valid range for the application.
- If handling historical dates, be aware of how your local timezone affects parsing and representation of dates.
- Update the SimpleDateFormat pattern to correctly match the date string.
Common Mistakes
Mistake: Assuming all years will return positive milliseconds regardless of the epoch.
Solution: Always check if the date being parsed falls before the Unix epoch and consider adjusting your handling logic.
Mistake: Using the wrong date format pattern in SimpleDateFormat.
Solution: Verify that your format pattern matches the date string you are parsing to ensure accurate date interpretation.
Helpers
- Java SimpleDateFormat
- SimpleDateFormat parse negative value
- getTime() returns negative
- Java date parsing issues
- Unix epoch in Java