Java: Get week number from any date?

2020-02-25 22:59发布

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 calendar
8条回答
趁早两清
2楼-- · 2020-02-25 23:41

WeekFields

This method that I created works for me in Java 8 and later, using WeekFields, DateTimeFormatter, LocalDate, and TemporalField.

Don't forget to format your date properly based on your use case!

public int getWeekNum(String input) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yy");   // Define formatting pattern to match your input string.
    LocalDate date = LocalDate.parse(input, formatter);                     // Parse string into a `LocalDate` object.

    WeekFields wf = WeekFields.of(Locale.getDefault()) ;                    // Use week fields appropriate to your locale. People in different places define a week and week-number differently, such as starting on a Monday or a Sunday, and so on.
    TemporalField weekNum = wf.weekOfWeekBasedYear();                       // Represent the idea of this locale’s definition of week number as a `TemporalField`. 
    int week = Integer.parseInt(String.format("%02d",date.get(weekNum)));   // Using that locale’s definition of week number, determine the week-number for this particular `LocalDate` value.

    return week;
}
查看更多
手持菜刀,她持情操
3楼-- · 2020-02-25 23:44

You can use that, but you have to parse the date value to proper date format using SimpleDateFormatter of java API. You can specify any format you want. After that you can do you manipulation to get the week of the year.

查看更多
登录 后发表回答