Skip to content
Advertisement

Java: Get week number from any date?

I have a small program that displays the current week from todays date, like this:

GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);

And then a JLabel that displays the week number:

JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));

So right now I’d like to have a JTextField where you can enter a date and the JLabel will update with the week number of that date. I’m really not sure how to do this as I’m quite new to Java. Do I need to save the input as a String? An integer? And what format would it have to be (yyyyMMdd etc)? If anyone could help me out I’d appreciate it!

Advertisement

Answer

Do I need to save the input as a String? An integer?

When using a JTextField, the input you get from the user is a String, since the date can contain characters like . or -, depending on the date format you choose. You can of course also use some more sophisticated input methods, where the input field already validates the date format, and returns separate values for day, month and year, but using JTextField is of course easier to start with.

And what format would it have to be (yyyyMMdd etc)?

This depends on your requirements. You can use the SimpleDateFormat class to parse any date format:

String input = "20130507";
String format = "yyyyMMdd";

SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);

But more likely you want to use the date format specific to your locale:

import java.text.DateFormat;

DateFormat defaultFormat = DateFormat.getDateInstance();
Date date = defaultFormat.parse(input);

To give the user a hint on which format to use, you need to cast the DateFormat to a SimpleDateFormat to get the pattern string:

if (defaultFormat instanceof SimpleDateFormat) {
   SimpleDateFormat sdf = (SimpleDateFormat)defaultFormat;
   System.out.println("Use date format like: " + sdf.toPattern());
}

The comment by @adenoyelle above reminds me: Write unit tests for your date parsing code.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement