The following illustrates getting season name by month and date in Java.
setLenient(false): Allow strict checking of the date, so that month cannot be greater than 12 and February contains no more than < 30 days always etc.
f.parse(m+"-"+d): This creates a java.util.Date object from given month and date in the specified format.
date.after(): This method checks if the parameter date is after the calling date, similiarily date.before() checks if the parameter date is before the calling date with the help of which we determine the season.
new SimpleDateFormat("MM-dd"): Create an object for the SimpleDateFormat class of the format month-date.import java.util.*;
import java.text.*;
class CheckSeason
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the month and day");
int m=s.nextInt();
int d=s.nextInt();
SimpleDateFormat f=new SimpleDateFormat("MM-dd");
f.setLenient(false);
try
{
Date date=f.parse(m+"-"+d);
if(date.after(f.parse("04-21")) && date.before(f.parse("06-21"))){
System.out.println("Spring");
}
else if(date.after(f.parse("06-20")) && (date.before(f.parse("09-23"))))
{
System.out.println("Summer");
}
else if(date.after(f.parse("09-22")) && date.before(f.parse("12-22")))
{
System.out.println("Fall");
}
else System.out.println("Winter");
}catch(Exception e){
System.out.println("Invalid month/date "+e);
}
}
}
setLenient(false): Allow strict checking of the date, so that month cannot be greater than 12 and February contains no more than < 30 days always etc.
f.parse(m+"-"+d): This creates a java.util.Date object from given month and date in the specified format.
date.after(): This method checks if the parameter date is after the calling date, similiarily date.before() checks if the parameter date is before the calling date with the help of which we determine the season.
No comments:
Post a Comment