Commons CLI 模拟支持国际化打印日期和时间小程序

CLI
本文将演示怎样利用 Commons CLI 模拟一个支持国际化打印日期和时间的命令行小程序。

小程序描述

该小程序是一个命令行程序,通过运行程序时指定命令行参数来控制是否打印时间(默认只打印日期),是否进行国际化显示日期。支持可选选项:

  • -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
睡眠和休息丧失了时间,却取得了明天工作的精力。 —— 毛泽东
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号