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!
Java 1.8 provides you with some new classes in package
java.time
:Most legacy calendars can easily be converted to
java.time.ZonedDateTime
/java.time.Instant
by interoperability methods, in your particular caseGregorianCalendar.toZonedDateTime()
.tl;dr
ISO 8601 standard week
If you want the standard ISO 8601 week, rather than a localized definition of a week, use the
YearWeek
class found in the ThreeTen-Extra project that adds functionality to the java.time classes built into Java 8 and later.First, get today's date. The
LocalDate
class represents a date-only value without time-of-day and without time zone.A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of
continent/region
, such asAmerica/Montreal
,Africa/Casablanca
, orPacific/Auckland
. Never use the 3-4 letter abbreviation such asEST
orIST
as they are not true time zones, not standardized, and not even unique(!).Or let the user specify a date by typing a string. Parsing string input of a date is covered in many other Questions and Answers. Simplest is to have the user use standard ISO 8601 format, YYYY-MM-DD such as
2017-01-23
.For other formats, specify a
DateTimeFormatter
for parsing. Search Stack Overflow for many many examples of using that class.Get the
YearWeek
.To create a string, consider using the standard ISO 8601 format for year-week, yyyy-Www such as
2017-W45
. Or you can extract each number.YearWeek::getWeek
– Gets the week-of-week-based-year field.YearWeek::getYear
– Gets the week-based-year field.Other definitions of week
The above discussion assumes you go by the ISO 8601 definition of weeks and week-numbering. If instead you want an alternate definition of week and week-numbering, see the Answer by Mobolaji D. using a locale’s definition.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.this one worked for me
Works fine and return week for current realtime
You can store the date as a String, and the user can enter it in pretty much any format you specify. You just need to use a
DateFormat
object to interpret the date that they enter. For example, see the top answer on Convert String to Calendar Object in Java.To read the date from a
JTextField
, you could replace that with something like:Then you just need to read the week number from
cal
in the same way you showed in the question. (This is a simplified example. You'd need to handle the potentialParseException
thrown by theDateFormat
parse
method.)When using a
JTextField
, the input you get from the user is aString
, 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 usingJTextField
is of course easier to start with.This depends on your requirements. You can use the SimpleDateFormat class to parse any date format:
But more likely you want to use the date format specific to your locale:
To give the user a hint on which format to use, you need to cast the
DateFormat
to aSimpleDateFormat
to get the pattern string:The comment by @adenoyelle above reminds me: Write unit tests for your date parsing code.