Java: Get week number from any date?

后端 未结 8 1014
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 09:38

I have a small program that displays the current week from todays date, like this:

GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calend         


        
8条回答
  •  自闭症患者
    2020-12-30 10:07

    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;
    }
    

提交回复
热议问题