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
:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.IsoFields;
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.printf("Week %d%n", now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
Most legacy calendars can easily be converted to java.time.ZonedDateTime
/ java.time.Instant
by interoperability methods, in your particular case GregorianCalendar.toZonedDateTime()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With