You can achieve what you want with SimpleDateFormat , if the format is known and uniformed.
public class TestParse {
public static void main(String[] args) {
String myDate = "17-Mar-2006";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date = null;
try {
date = simpleDateFormat.parse(myDate);
} catch (ParseException e) {
e.printStackTrace();
}
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());
}
}
EDIT:
Added more information based on question change
the method getStringFromDate
produces a formatted date of 17-Mar-2006
public class TestParse {
public static void main(String[] args) {
String myDate = "17-Mar-2006";
Date date = getDateFromString(myDate);
// Set the Calendar
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
// format date
String formattedDate = getStringFromDate(calendar);
System.out.printf("The formatted date is : %s & the dates are equal %s%n", formattedDate, formattedDate.equals(myDate));
}
public static String getStringFromDate(GregorianCalendar calendar) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
simpleDateFormat.setCalendar(calendar);
return simpleDateFormat.format(calendar.getTime());
}
public static Date getDateFromString(String input) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
Date date = null;
try {
date = simpleDateFormat.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
Your Stockmarket class Fixed type on format
public class Stockmarket {
// instance variables
private GregorianCalendar date;
private double opening;
private double closing;
public Stockmarket(String dt, double opening, double closing) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
Date d = null;
try {
d = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
cal.setTime(d);
this.date = cal;
this.opening = opening;
this.closing = closing;
}
public String date() {
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
df.setCalendar(this.date);
String date = df.format(this.date.getTime());
return date;
}
}
Testing Class
public class TestParse {
public void doTest()
{
Stockmarket stockmarket1 = new Stockmarket("17-Mar-2006",500,600);
stockmarket1.date();
System.out.println(stockmarket1.date());
Stockmarket stockmarket2 = new Stockmarket("16-Jan-2002",500,600);
stockmarket2.date();
System.out.println(stockmarket2.date());
Stockmarket stockmarket3 = new Stockmarket("15-Jun-2003",500,600);
stockmarket3.date();
System.out.println(stockmarket3.date());
}
public static void main(String[] args) {
TestParse testParse = new TestParse();
testParse.doTest();
}
}