Is there a simple way how to get week of year information from a Date object or from millis time in GWT on the client side?
Something like this:
Date date = new Date();
Date yearStart = new Date(date.getYear(), 0, 0);
int week = (int) (date.getTime() - yearStart.getTime())/(7 * 24 * 60 * 60 * 1000);
Note that this will give you a week in a Date object, which has no time zone information. When you use it, you may have to adjust it using the time zone information.
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using the modern API:
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now(ZoneId.systemDefault());
int weekOfYear = date.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
System.out.println(weekOfYear);
}
}
Output:
18
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
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