3

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?

ps-aux
  • 11,627
  • 25
  • 81
  • 128
  • Find a way using JavaScript [GitHub - getWeek.js](https://gist.github.com/dblock/1081513l) and call from GWT JSNI. – Braj May 29 '14 at 18:21

3 Answers3

3

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.

Andrei Volgin
  • 40,755
  • 6
  • 49
  • 58
  • If I know the offset from `date.getTimezoneOffset()` how to I include it into the calculation? – ps-aux May 29 '14 at 17:50
  • date.getTime() - yearStart.getTime() + date.getTimezoneOffset() * 60 * 1000, because TimezoneOffset is measured in minutes. – Andrei Volgin May 29 '14 at 17:54
  • Even though not 100% precise (as I believe there are different definitions what counts as a first week in year for different locales) I will use this solution for now. – ps-aux Jun 14 '14 at 12:32
1

java.time

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

How to do it with GWT object not sure but because GWT code is converted to javascript at compile time, so you could make something like this:

http://javascript.about.com/library/blweekyear.htm

Tadas Davidsonas
  • 1,859
  • 4
  • 16
  • 19