In: Computer Science
In Java, how can I convert a string user input for example a student starts a uni degree in "Winter/2022", to a date type, and then once I have done that, add 3 years to that value, and changing the season, so for example Student Started: Winter/2022 and Student Finished: Summer/2025. Is there any possible way to do this?
Thank you.
code.......
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
public class StringToDate {
public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
System.out.println("Enter current date in format (dd/mm/yyyy) with
season put space between date and season");
String input=sc.nextLine();
String date=input.substring(0,input.indexOf(' '));// Retrieving
data part from the given string
String season=input.substring(input.indexOf(' ')+1);// Retrieving
season part from the given string
//taking the position of last slash or hypen in the inputted
string
int pos=input.lastIndexOf('/');// this method returns -1 if / is
not present.
int yearPart=Integer.parseInt(input.substring(pos+1,pos+5));
System.out.println("Enter the year to which will be added to the
current year:");
int yearAdd=sc.nextInt();
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(date);
System.out.println("Current date "+date1+" Season:"+season);
//loop to decide the season change
int i=1;
while(i<=yearAdd){
if(i%3==0)
{
if(season.equalsIgnoreCase("Summer"))
season="winter";
else
season="summer";
}
i++;
}
System.out.println("Date after "+yearAdd+" years");
yearPart=yearPart+yearAdd;
String updateDate=date.substring(0,pos-1)+"/"+yearPart;
date1=new SimpleDateFormat("dd/MM/yyyy").parse(updateDate);
System.out.println("Current date "+date1+" Season:"+season);
}
}
// Input and Output part
Enter current date in format (dd/mm/yyyy) with season put space
between date and season
12/12/2020 Winter
Enter the year to which will be added to the current year:
3
Current date Sat Dec 12 00:00:00 IST 2020 Season:Winter
Date after 3 years
Current date Thu Jan 12 00:00:00 IST 2023 Season:summer