该小程序是一个命令行程序,通过运行程序时指定命令行参数来控制是否打印时间(默认只打印日期),是否进行国际化显示日期。支持可选选项:
-t 指定是否需要打印时间。如果需要打印时间,则指定该选项
-c 指定国家代码,用来创建给定的日期
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
* @date 2018-01-24 13:45
*/
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() };
}
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") );
}
public 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 {
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", local);
System.out.println( sdf.format(date) );
}
}
}运行小程序,输出如下:
java.exe com.hxstrive.cli.Demo3 -t -c CN
参数:[-t, -c, CN]
2021-12-13 23:23:32
Process finished with exit code 0