该示例用于通过选项控制输出日期和时间,并且还支持通过 -c 实现国际化。其中可选选项:
-t 指定是否需要打印时间。如果需要打印时间,则指定该选项
-c 指定国家代码,用来创建给定的日期
程序运行方式:
$ java Demo3 -t -c US
示例代码:
package com.hxstrive.cli;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
/**
* 一个用于输出当前日期和时间,支持国际化。
*
* 可选选项:
* -t 指定是否需要打印时间。如果需要打印时间,则指定该选项
* -c 指定国家代码,用来创建给定的日期
*
* @author Administrator
*/
public class Demo3 {
public static void main(String[] args) throws Exception {
new Demo3(args);
}
public Demo3(String args[]) throws Exception {
// 模拟命令行参数
if ( args.length <= 0 ) {
//args = new String[] { "-t", "-c", Locale.US.getCountry() };
args = new String[] { "-c", Locale.US.getCountry() };
}
System.out.println("参数:" + Arrays.toString(args) );
// 创建选项
Options options = new Options();
options.addOption("t", false, "print the date and time");
options.addOption("c", true, "country code");
// 解析参数
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// 获取 c 选项的值
String countryCode = cmd.getOptionValue("c");
printDate(countryCode, cmd.hasOption("t") );
}
private void printDate(String countryCode, boolean isPrintTime) {
// 构造Calendar
Locale local;
Calendar calendar;
if ( null == countryCode ) {
// 默认国家代码
local = Locale.CHINA;
calendar = Calendar.getInstance();
} else {
local = new Locale(Locale.CHINESE.getLanguage(), countryCode);
calendar = Calendar.getInstance(local);
}
// 输出日期
if ( isPrintTime ) {
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", local);
System.out.println( sdf.format(date) );
} else {
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", local);
System.out.println( sdf.format(date) );
}
}
}运行程序,输出如下:
参数:[-c, US] 2023-06-26