I have a scenario like
"DAY 316 OF YEAR 1998".
how can i get the exact date and month with the above input? Any ideas?
In Java, how can i achieve this? Please help.
I have a scenario like
"DAY 316 OF YEAR 1998".
how can i get the exact date and month with the above input? Any ideas?
In Java, how can i achieve this? Please help.
There are any number of ways you might achieve this, based on what you have available.
For example. Based on the String
in your example, you could use a SimpleDateFormat
to simple parse the String
back to a Date
object, which is probably the easiest solution I can think of...
try {
String value = "DAY 316 OF YEAR 1998";
SimpleDateFormat sdf = new SimpleDateFormat("'DAY' DDD 'OF YEAR' yyyy");
Date date = sdf.parse(value);
System.out.println(date);
} catch (ParseException exp) {
exp.printStackTrace();
}
Once you have a Date
object, you can use Calendar
to extract various parts of the Date
object or simple use another DateFormat
to format the value...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("Day of Month = " + cal.get(Calendar.DATE));
// Note, MONTH is 0 indexed...
System.out.println("Month = " + (cal.get(Calendar.MONTH) + 1));
System.out.println("Formatted = " + DateFormat.getDateInstance().format(date));
So you should end up with, something like...
Day of Month = 12
Month = 11
Formatted = 12/11/1998
You should first tell whether the year is 1998
, or 2098
, or something else.
Apart from that, you can achieve what you want using the Calendar API. The constants of your interest are:
Create a Calendar instance, using Calendar.getInstance(TimeZone)
. Set the YEAR
(1998 or 2098, whatever), and DAY_OF_YEAR
(316) using above mentioned constants, and Calendar#set(field, value)
method.
I'm not sure if there is a better way, but what you could try is to use the following code line:
Calendar mycal = new GregorianCalendar(1998, Calendar.JANUARY, 1);
int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH);
This returns the number of days of the month you input. Go from January untill December (increasing/changing your mycal
) and substract everything from your daynumber, untill you have a negative number. That would be your month.
Try something like this using the Calender
:-
Date d;
Calendar c= Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
Use RegExps to extract the data you need from that string and use the Date/Calendar class to point to that moment. I guess is a homework so I won't give you any code snippets, you must work it out on your own.