How to Convert Time to String in Java
- 1). Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Application" from the list on the right-hand side of the screen. A new source code file appears in the NetBeans text editor. The source code file contains an empty main method.
- 2). Create a new Date object. When a new Date object is created, it captures the current time, rounded off to the nearest millisecond. To create a Date object, write the following within the curly brackets of the main method:
Date currentDate = new Date (); - 3). Create a SimpleDateFormat object, which will be used to format the Date object created in the previous step. To create a SimpleDateObject that formats the data to display month first, then day and finally year, write the following statement below the one written in the previous step:
SimpleDateFormat dF = new SimpleDateFormat("MMddyyyy"); - 4). Create a StringBuilder object that will convert the Date object into a string. Write the following statement below the statement written in the previous step to convert the Date object into a string:
StringBuilder current = new StringBuilder(dF.format(currentDate) ); - 5). Print out the string using the println function. Write the following statement below the one written in the previous step:
System.out.println( "Current Date: '" + current); - 6). Execute the program by pressing the green "Play" button. The program will output the current time, which will look something like this:
Current Date: 11122013
Source...