I am looking at a website to learn Java and this is one of the exercises.
Write a program that will show different time and date information based on what number you send it. The codes are:
0 - number of milliseconds since January 1, 1970
1 - number of seconds since January 1, 1970
2 - number of days since January 1, 1970
3 - current date and time
So if I type: java prob 2
I want to see: days since January 1, 1970: 10727
I started it and used a switch statement. I am pretty sure I need to use the Date class in some way but I do not know how to put it together. If someone can show me how to do one, that would be very helpful.
public class prob4
{
public static void main(String args[])
{
String ArgumentFromCommandLine = args[0];
int time = Integer.parseInt(ArgumentFromCommandLine);
switch ( time )
{
case 0:
???;
break;
case 1:
???;
break;
case 2:
???;
break;
case 3:
???;
break;
default:
System.out.println("Invalid");
}
}
}
Probably best to save 0 for invalid. No need to create a string variable before parse to int. Best check how parse handles non numeric. Start by reading the methods of Date, avoiding the SQL Date. Date (Java Platform SE 8 )
The one desired result is in the listed methods. Fill that in.
Integer.parseInt has a funny side effect though. It will convert 000 to 0, 03 to 3 and so on.
import java.util.Date; // mandatory only for the "current date and time" part
public class prob4
{
public static void main(String args[])
{
String ArgumentFromCommandLine = "";
int time = 0;
// exit program if the supplied argument is not an integer OR
// if no or too many arguments were supplied
if (args.length == 1) {
try {
ArgumentFromCommandLine = args[0];
time = Integer.parseInt(ArgumentFromCommandLine);
} catch (NumberFormatException e) {
System.err.println("Argument " + args[0] + " must be an integer.");
System.exit(1);
}
}
else {
System.err.println("No or too many arguments were supplied.");
System.exit(1);
}
// collect all values
Long utms = System.currentTimeMillis(); // UNIX time in milliseconds
Long uts = utms / 1000; // UNIX time in seconds
Long utd = uts / 86400; // UNIX time in days
Date dateandtime = new Date(); // Current date and time, default format
// print requested value
switch ( time )
{
case 0:
System.out.println("Milliseconds since 1970: " + utms);
break;
case 1:
System.out.println("Seconds since 1970: " + uts);
break;
case 2:
System.out.println("Days since 1970: " + utd);
break;
case 3:
System.out.println("Current date and time: " + dateandtime);
break;
default:
System.out.println("Invalid");
}
}
}
Well, in the land of int there are just leading bits that everyone ignores, no leading decimal zeroes.
Integer.parseInt() does not tolerate white space, just -\{0,1\}[0-9]\(1,n\} where the value must fit in 32 bits, signed. The value of n here is variable, as you can have leading zeroes in any quantity. Minus zero does not bother it, is just zero. Integer (Java Platform SE 6), int)