Java Date Class


 
Thread Tools Search this Thread
Top Forums Programming Java Date Class
# 1  
Old 11-09-2014
Java Date Class

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.

Code:
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");
    }
	
    }

}

# 2  
Old 11-09-2014
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. https://docs.oracle.com/javase/8/doc...util/Date.html

The one desired result is in the listed methods. Fill that in.
# 3  
Old 11-09-2014
Java

Integer.parseInt has a funny side effect though. It will convert 000 to 0, 03 to 3 and so on.
Code:
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");
    }

    }

}

This User Gave Thanks to junior-helper For This Post:
# 4  
Old 11-09-2014
Quote:
Originally Posted by junior-helper
Integer.parseInt has a funny side effect though. It will convert 000 to 0, 03 to 3 and so on.
Code:
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");
    }

    }

}

Oh, thank you so much! That really helps me a lot. Smilie
# 5  
Old 11-12-2014
Well, in the land of int there are just leading bits that everyone ignores, no leading decimal zeroes. Smilie

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)

Last edited by DGPickett; 11-12-2014 at 04:32 PM..
# 6  
Old 11-12-2014
Quote:
Originally Posted by DGPickett
...
I wonder, does an argument of '' (empty string) blow up or act like 0?
Looks like it blows up:

Code:
$
$ cat -n ParseInteger.java
     1  public class ParseInteger {
     2      public static void main (String[] args) {
     3          if (args.length == 1) {
     4              String strParam = args[0];
     5              System.out.println("Input string parameter                  = [" + strParam + "]");
     6              System.out.print  ("Integer value of input string parameter = ");
     7              System.out.println(Integer.parseInt(strParam));
     8          }
     9      }
    10  }
$
$ javac ParseInteger.java
$
$ java ParseInteger "-000456"
Input string parameter                  = [-000456]
Integer value of input string parameter = -456
$
$ java ParseInteger "-00"
Input string parameter                  = [-00]
Integer value of input string parameter = 0
$
$ java ParseInteger "+00"
Input string parameter                  = [+00]
Integer value of input string parameter = 0
$
$ java ParseInteger "000"
Input string parameter                  = [000]
Integer value of input string parameter = 0
$
$ java ParseInteger "1234"
Input string parameter                  = [1234]
Integer value of input string parameter = 1234
$
$ java ParseInteger "+123"
Input string parameter                  = [+123]
Integer value of input string parameter = 123
$
$ java ParseInteger ""
Input string parameter                  = []
Integer value of input string parameter = Exception in thread "main" java.lang.NumberFormatException: For input string: ""
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at ParseInteger.main(ParseInteger.java:7)
$
$

# 7  
Old 11-12-2014
Yes, I meant to remove that, the API spec is very specific. Have to link wrapper it:

Integer (Java Platform SE 6)

Last edited by DGPickett; 11-12-2014 at 04:37 PM..
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Programming

Simplify setter and getter of java class

I am trying to verify my understanding on setter and getter on java class with this example: //MaximumFinder2.java import java.util.Scanner; public class MaximumFinder2 { public static void main (String args) { Scanner input = new Scanner(System.in); ... (6 Replies)
Discussion started by: yifangt
6 Replies

2. UNIX for Advanced & Expert Users

Get pointer for existing device class (struct class) in Linux kernel module

Hi all! I am trying to register a device in an existing device class, but I am having trouble getting the pointer to an existing class. I can create a class in a module, get the pointer to it and then use it to register the device with: *cl = class_create(THIS_MODULE, className);... (0 Replies)
Discussion started by: hdaniel@ualg.pt
0 Replies

3. Programming

Link array to class java

Hi, I need help to Link array from one class to another class Firstly CSVParser Class what it did is load csv file and store into array Secondly WarehouseItem where each record is store How can I get a list of array that I load to CSVParser Class and store them to WarehouseItem and... (0 Replies)
Discussion started by: guidely
0 Replies

4. Programming

Help in JAVA main and class

Is anyone know how to write a class in separate file? While method does it needs to be contained in a printwriter class? Can I have the format of the printwriter class as a reference? Thanks a lot. (1 Reply)
Discussion started by: eel
1 Replies

5. Programming

how abstract class differs in Java and C++?

hello all, i want to know if there is any difference in working and syntax declaration of abstract class in Java and C++. (1 Reply)
Discussion started by: haravivar
1 Replies

6. Fedora

Help, how to dynamicly load java class

Hi, everyone: I'm trying to connect to DB using JDBC on fedora. I have successfully installed jdk and it's ok to run common java program. The environment variables: JAVA_HOME=/installed/mycoy/jdk1.6.0 PATH=$JAVA_HOME/bin:$PATH... (3 Replies)
Discussion started by: mycoy
3 Replies

7. Shell Programming and Scripting

call constructor of java class in script

Hi, Is it possible to call the constructur of a java class in a shell script? I know you can call static methods, but can you also call the constructor? tnx. (1 Reply)
Discussion started by: thebladerunner
1 Replies

8. Shell Programming and Scripting

Function loading in a shell scripting like class loading in java

Like class loader in java, can we make a function loader in shell script, for this can someone throw some light on how internally bash runs a shell script , what happenes in runtime ... thanks in advance.. (1 Reply)
Discussion started by: mpsc_sela
1 Replies

9. Shell Programming and Scripting

Running java class with a cron

Hello everybody, I have a problem about running a java class with a cron : I have Cron.txt file which has : 0,5,10,15,20,25,30,35,40,45,50,55 * * * * CronJava.txt I have CronJava.txt wihich has : cd ias/j2ee/SapAktarim/applications/SapAktarim/SapAktarim/WEB-INF/classes/;java -classpath... (3 Replies)
Discussion started by: UBGandalf
3 Replies
Login or Register to Ask a Question