java从命令行参数输入一个日期,如“2013-3-20”,计算它与今日之间的天数间隔。
时间: 2024-11-09 10:31:28 浏览: 13
在Java中,你可以通过`java.util.Date`类和`java.text.SimpleDateFormat`来处理从命令行参数获取的日期并计算与今天的天数差异。以下是一个简单的步骤:
1. **获取命令行参数**:
首先,你需要从`System`类的`args`数组中获取用户提供的日期字符串。例如:
```java
String inputDate = args[0];
```
2. **解析日期字符串**:
使用`SimpleDateFormat`将输入的"yyyy-MM-dd"格式的字符串转换为`Date`对象:
```java
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date inputDateObject = null;
try {
inputDateObject = formatter.parse(inputDate);
} catch (ParseException e) {
System.out.println("Invalid date format. Please use 'yyyy-MM-dd'.");
return;
}
```
3. **获取当前日期**:
创建一个`Calendar`对象,并将其设置为今天:
```java
Calendar currentDateCalendar = Calendar.getInstance();
Date currentDate = currentDateCalendar.getTime();
```
4. **计算天数差**:
使用`Calendar`的`getTimeDifference`方法计算两个日期之间的差异(以日为单位),然后取绝对值得到天数:
```java
long diffInMilliseconds = currentDateCalendar.getTimeInMillis() - inputDateObject.getTime();
int daysDifference = Math.abs((int) (diffInMilliseconds / (1000 * 60 * 60 * 24)));
```
5. **打印结果**:
最后,打印出天数差异:
```java
System.out.println("Days difference between the two dates is: " + daysDifference);
```
完整示例代码如下:
```java
public class Main {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java Main <date_string>");
return;
}
String inputDate = args[0];
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date inputDateObject;
try {
inputDateObject = formatter.parse(inputDate);
} catch (ParseException e) {
System.out.println("Invalid date format. Please use 'yyyy-MM-dd'.");
return;
}
Calendar currentDateCalendar = Calendar.getInstance();
Date currentDate = currentDateCalendar.getTime();
long diffInMilliseconds = currentDateCalendar.getTimeInMillis() - inputDateObject.getTime();
int daysDifference = Math.abs((int) (diffInMilliseconds / (1000 * 60 * 60 * 24)));
System.out.println("Days difference between the two dates is: " + daysDifference);
}
}
```
记得运行此程序时,提供格式正确的日期作为命令行参数。
阅读全文