Lukie Al-Saba Lukie Al-Saba - 2 months ago 12
Java Question

How does this date and time snippet work?

I just started taking a computer science class a week ago, and I found this code to get the date and time. But I don't fully understand what everything in this means. If anyone could clarify that would be awesome! :)

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.print("Date: ");
System.out.println(sdf.format(resultdate));

Answer

long yourmilliseconds = System.currentTimeMillis();

get the number of milliseconds from the System

Date resultdate = new Date(yourmilliseconds);

Creates a date from it. These two lines could be changed to

Date resultdate = new Date();

As dates in JDK1.7 and previous did not have any intrinsic formatting a formatting class is used

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");

This is the pattern it will print as

System.out.println(sdf.format(resultdate));

Now we call the formatting method and print it out.