Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Get week number from any date?

Tags:

java

calendar

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!

like image 651
Boxiom Avatar asked May 07 '13 12:05

Boxiom


1 Answers

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().

like image 77
user667 Avatar answered Nov 15 '22 12:11

user667