This question already has answers here:
Generate random date of birth
(15 answers)
Closed 8 years ago.
I want to generate a random date as string in format - yy-MM-dd for the given year.
assume if i pass the year it should give a random date of the year.
I went through Random() as well as nextInt() but not sure how to get this
could you please help me on how to achieve this?
Thanks.
You can use a Calendar to do that:
final Calendar cal = Calendar.getInstance();
final Random rand = new Random();
final SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, rand.nextInt(cal.getActualMaximum(Calendar.DAY_OF_YEAR)) + 1);
System.out.println(format.format(cal.getTime()));
cal.getActualMaximum(Calendar.DAY_OF_YEAR) will return the number of the last day of the year the Calendar is set to (2014 in this code).
rand.nextInt() will return a number between 0 (inclusive) and the number of the last day (exclusive). You have to add 1 because the field Calendar.DAY_OF_YEAR starts at 1.
cal.set() will set the given field of the Calendar to the value given as the second argument. It is used here to set the year to 2014, and the day of the year to the random value.
SimpleDateFormat is used to print the date in the required format.
You can do with JSR-310 (Built in Java 8, but available to older versions)
public static LocalDate randomDateIn(int year) {
Year y = Year.of(year);
return y.atDay(1+new Random().nextInt(y.length()));
}
System.out.println(randomDateIn(2014));
prints something like
2014-05-21
If you want to work with random, this is how it works:
Random r=new Random();
int day=r.nextInt(30)+1; // (think of something yourself for implementing months with different amount of days)
int month=r.nextInt(11)+1; // (+1 because you don't want the zero)
However i see another answer, which if it works will probably save you a lot of time on implementing the days each month has.(and the leap year)
Related
This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Why is January month 0 in Java Calendar?
(18 answers)
Closed 3 years ago.
I have tried to compare to Dates the Birthdate and the Current date
and then I tried to get the age.
But the Current date Funtion begins with another Date than the given date
My Code:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
long ms = System.currentTimeMillis() - birthdate.getTimeInMillis();
double years = (((double)ms / 1000)/31536000) ;
System.out.print(years);
// years Shoud be 18 here but it returns 17.3
if (years > 18) {
// Code Block
}
else{
System.out.print("to Jung");
}
Check the Constructor on GregorianCalendar.
public GregorianCalendar(int year,
int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
year - the value used to set the YEAR calendar field in the calendar.
month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.
dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
You are creating a July 20th date, which is coincidentally offset by a single month, or approximately 0.08 years.
LocalDate birthdate = LocalDate.of(2001,06,20);
LocalDate currentdate = LocalDate.now();
int years = Period.between(birthdate , currentdate).getYears();
if (years >= 18) {
// Code
} else {
System.out.print("Sie sind zu Jung");
}
It Worked like this but I must change the hole code because everything was written with the GeorgianCalender.
I couldn't tell you why exactly your code, which should technically work, doesn't: there seems to be inaccuracies (leap days?) in the Calendar, or I'm missing something. Thanks to Compass, I know that I was missing something: months are 0-indexed in the constructor for Gregorian Calendar. 06 is July.
However, you shouldn't compare dates like this. If you don't want to use any other library, you can do this:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
GregorianCalendar today = new GregorianCalendar();
birthdate.add(Calendar.YEAR, 18);
System.out.print(birthdate.getTime().after(today.getTime()));
This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 8 years ago.
All I must do for this code is display the current year, month and day of the year using the GregorianCalendar class. for some reason everything is right but the month. The program returns the month as being 11 instead of 12. Any suggestions?
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
GregorianCalendar Calendar = new GregorianCalendar();
int year = Calendar.get (GregorianCalendar.YEAR);
int month = Calendar.get (GregorianCalendar.MONTH);
int day = Calendar.get (GregorianCalendar.DAY_OF_MONTH);
System.out.println("the current year is " + year);
System.out.println("the current month is " + month);
System.out.println("the current day is " + day);
}
Java stores the month numbers as 0-based in Calendar. When you use MONTH, 11 does represent December, so this is correct. You must add 1 to this output to convert to what we're used to -- a range of 1-12.
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0
just add +1, java is counting months starting from 0 i.e.
GregorianCalendar.JANUARY == 0
Calendar.MONTH is zero-based. Because of this it is 11.
From the API:
The first month of the year is JANUARY which is 0; the last depends on
the number of months in a year.
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 8 years ago.
public static int countWeeks() {
// setting dates
Calendar calStart = GregorianCalendar.getInstance();
calStart.set(2014, 8, 30);
Date dateStart = calStart.getTime();
Date dateEnd = new Date();
// count days and weeks
int diffInDays = Days.daysBetween(new DateTime(dateStart), new DateTime(dateEnd)).getDays(); // int weekNumber = (int) diffInDays / 7;
return weekNumber;
}
I'm trying to calculate the number of days and weeks between today and last week but I always get -3 as weekNumber. I have no idea what i'm doing wrong.
Thanks in advance.
First, I will assume that
int weekNumber = (int) diffInDays / 7;
is not commented since otherwise you would get a compilation error.
Now, as explained in my comment, by doing
calStart.set(2014, 8, 30);
You are setting the date at the end of setember, not of august. So, it is 3 weeks ahead of now, so you get a -3. Use the Calendar constants.
calStart.set(2014, Calendar.AUGUST, 30);
You set the startdate to Sep. 30th because te month is zero bases!
See the documentation from java.util.Calendar:
public final void set(int year,
int month,
int date) Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. Previous values of other calendar fields are
retained. If this is not desired, call clear() first. Parameters: year
- the value used to set the YEAR calendar field. month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0
for January. date - the value used to set the DAY_OF_MONTH calendar
field. See Also:
You are getting -3 as the weeknumber since you have commented that out so it showing some random value. Also note that 8 shows the September month not Aug since months are 0 based.
So if you are aiming at August month then you may try this:
calStart.set(2014, 7, 30);
^^-- This represents August month
If you are on Java 8 you can use the Java time API:
LocalDate start = LocalDate.of(2014, 8, 30);
LocalDate end = LocalDate.now();
long days = ChronoUnit.DAYS.between(start, end);
return (int) days / 7;
This question already has answers here:
Java: getMinutes and getHours
(13 answers)
Closed 8 years ago.
I want to get the current hour,minute, and second from the Date object.
This is my code:
Date date = new Date();
int hour = date.getHours();
But I get a kind of error, the getHours() part doesnt work. I get a "The method getHours() from the type Data is deprecated". What does that mean, and how do I get the hour,minutes, and seconds?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hours = cal.get(Calendar.HOUR_OF_DAY);
From Date javadoc:
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MINUTE).
Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone. The value returned is between 0 and 59.
I have homework that involves the user entering 2 integers (The month & The year) and I was wondering how to do that, I have searched a little in the calendar class documentation but I didn't find what I was searching for.
The main thing I'm tring to do is to print a calendar like the one in Windows where the only input I get from the user is the number of the month and year, I need to find a way to find weather the month is 31, 30, 29 or 28 days and the day in which that month started.
http://lifehacker.com/assets/2006/06/vista-windows-calendar.jpg this is what I want to do but as text without printing the days from other months .
You could use java.util.Date for this:
int month = 3 ; // Input
int year = 2012 ; // Input
Date date = new Date() ;
date.setMonth(month) ;
date.setYear(year) ;
But since Date is deprecated, you would have to use java.util.Calendar instead. The equivalent functions are:
Calendar.set(Calendar.MONTH, month) ;
Calendar.set(Calendar.YEAR, year) ;
Have a look at DateFormatSymbols. This has methods to retrieve the months. You can then use the index postion in the array (the month number) to get the month
String[] months = new DateFormatSymbols(Locale.getDefault()).getMonths();
System.out.println(months[0]);
System.out.println(months[11]);
As it's homework I'll let you work out why [0] gives Januaray and [11] gives December
Since this is homework, I'm not spilling out all the beans. You have to figure out the rest.
Without knowing what have you tried or what do you mean by finding a month, I think you want to obtain a Date object based in a year and a month.
The Calendar class was a right start. First of all, you should obtain an instance with the getInstance() method, considering the set(int field, int value) method in particular to set both the year and the month of that calendar.
If you're wondering how do you know which field you're setting, try the different constant values defined by Calendar itself (by convention, those are named in uppercase, just for you to find them).
In the end you just need to obtain that Date, through the getTime() method.
EDIT
Following the Calendar class approach and by using set, you can come up with the month you're searching.
Use methods such as getActualMaximum(int field) with Calendar.DAY_OF_MONTH. That's practically one of the answers. The other one is similar and I'm leaving it up to you.
Hint: Create a calendar and play with the fields, try setting the day of the month to 1 (the first day) and the current month to the one you need to get information from.
import java.util.Calendar;
import java.text.SimpleDateFormat;
class PrintCalendar {
public static void main(String args[]) {
Calendar c = Calendar.getInstance();
int month = 3;
int year = 2011;
c.set(year, month, 1); // Set c's time to first day of specified month/year
// Day of week (by numerical index) can also be obtained programmatically with c.get(Calendar.DAY_OF_WEEK)
System.out.println("First day of month falls on a " + new SimpleDateFormat("EEEE").format(c.getTime()));
// "Actual maximum" means the maximum in the current timeframe; that is, it will return 29 for a February in a leap year
System.out.println("Month has " + c.getActualMaximum(Calendar.DAY_OF_MONTH) + " days");
}
}