Reputation: 29
I'm a novice Java student. I have only been studying programming for a few months at school, and so I am currently pretty bad at it, and often feel stuck doing my assignments.
Anyway, I have a question regarding an assignment. I have been looking around and not quite finding the answers I need, so I was hoping to find some help on here. It would be much appreciated. My assignment goes like this: "Write a program that creates a Date object and a Random object. Use the Random object to set the elapsed time of the Date object in a loop to 10 long values between 0
and 100000000000
and display the random longs and the corresponding date and time."
We were just introduced to the classes java.util.Random
and java.util.Date
to work with this assignment, and are expected to use them to create the needed Date and Random objects.
The only things I really know how to do for this assignment are how to start the code:
public class RanDate {
public static void main(String[] args) {
And how to create the loop:
for (int i = 0; i <= 10; i++) {
I'm sorry if my question was too vague, or if I didn't ask something properly. This is my first time asking for help on this site. Thank you in advance for your help.
Upvotes: 2
Views: 8565
Reputation: 614
Try this code. I think the assignment asks for the long to be the value in the date object, but I'm not shure.
public static void main(String[] args) {
Long max =0L;
Long min =100000000000L;
//Use the date format that best suites you
SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i <= 10; i++) {
Random r = new Random();
Long randomLong=(r.nextLong() % (max - min)) + min;
Date dt =new Date(randomLong);
System.out.println("Generated Long:"+ randomLong);
System.out.println("Date generated from long: "+spf.format(dt));
}
}
Sample Output:
Generated Long:68625461379
Date generated from long: 05/03/1972
Upvotes: 2
Reputation: 44398
How about this?
Random rnd = new Random();
Date date = new Date(Math.abs(System.currentTimeMillis() - rnd.nextLong()));
System.out.println(date.toString());
Just subtract the actual time System.currentTimeMillis()
and random generated long number with rnd.nextLong()
. It's better finally wrap it all to Math.abs()
.
Upvotes: 4