0

I'm have an application which run from command line. As one of it's parameters it have a date from which application should start to process some data. Date can have two different formats yyyy-MM-dd and yyyy-MM-dd HH:mm:ss. But when I run application with date in second format (for example 2012-04-18 15:05:08)it use space between -dd and HH as parameter delimiter. And I get exception

No argument is allowed: 15:05:08

I can wrap a date in quotes in command line. But is there other way to do so, without wrapping it?

For parsing command line arguments I'm using org.kohsuke.args4j library. Any suggestions?

atish shimpi
  • 4,873
  • 2
  • 32
  • 50
user2281439
  • 673
  • 2
  • 11
  • 19
  • Can you change format to yyyy-MM-dd_HH:mm:ss? Otherwise you can concatenate arg[0] and arg[1] – svz Dec 11 '14 at 12:10

2 Answers2

1

Just add some validation on the array to avoid null pointer exception

public static void main(String[] args) {
    SimpleDateFormat sdf;
    String in;
    if(args.length = 1) {
     in = args[0];
     sdf = new SimpleDateFormat("yyyy-MM-dd");
    } else if(args.lenth = 2)
     in = args[0] + " " + args[1];
     sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
    }


    if(args.length > 0) {
     Date date = sdf.parse(in);
     System.out.println("date:" + date);
    }
  }
rbeltrand
  • 108
  • 3
  • Yes, but my program have a lot of command line arguments, and it will be a little mess, to check if one or two args related to this parameter. But also thank you for idea. – user2281439 Dec 12 '14 at 13:28
0

When there is a space in the date, for example 2014-12-11 13:08:08 then you must put quotes around it on the command line, otherwise the command prompt will see it as two separate arguments.

Ofcourse you can change your program so that the date and time will be handled as two separate arguments:

public static void main(String[] args) {
    String date = args[0];
    String time = args[1];

    System.out.println("The date is: " + date);
    System.out.println("The time is: " + time);

    String dateTime = date + " " + time;
    System.out.println("The date and time: " + dateTime);
}

(You can find out for yourself how to do that with args4j).

Jesper
  • 202,709
  • 46
  • 318
  • 350