Java: Get week number from any date?

后端 未结 8 987
隐瞒了意图╮
隐瞒了意图╮ 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

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

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题