How to get start and end date of a year?

前端 未结 15 1760
清酒与你
清酒与你 2021-02-05 02:57

I have to use the Java Date class for this problem (it interfaces with something out of my control).

How do I get the start and end date of a year and then

相关标签:
15条回答
  • 2021-02-05 03:31

    An improvement over Srini's answer.
    Determine the last date of the year using Calendar.getActualMaximum.

    Calendar cal = Calendar.getInstance();
    
    calDate.set(Calendar.DAY_OF_YEAR, 1);
    Date yearStartDate = calDate.getTime();
    
    calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR));
    Date yearEndDate = calDate.getTime();
    
    0 讨论(0)
  • 2021-02-05 03:32

    I assume that you have Date class instance and you need to find first date and last date of the current year in terms of Date class instance. You can use the Calendar class for this. Construct Calendar instance using provided date class instance. Set the MONTH and DAY_OF_MONTH field to 0 and 1 respectively, then use getTime() method which will return Date class instance representing first day of year. You can use same technique to find end of year.

        Date date = new Date();
        System.out.println("date: "+date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
    
        System.out.println("cal:"+cal.getTime());
    
        cal.set(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
    
        System.out.println("cal new: "+cal.getTime());
    
    0 讨论(0)
  • 2021-02-05 03:33

    java.time

    Using java.time library built into Java 8 and later. Specifically the LocalDate and TemporalAdjusters classes.

    import java.time.LocalDate
    import static java.time.temporal.TemporalAdjusters.firstDayOfYear
    import static java.time.temporal.TemporalAdjusters.lastDayOfYear
    
    LocalDate now = LocalDate.now(); // 2015-11-23
    LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01
    LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31
    

    If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like

    lastDay.atStartOfDay(); // 2015-12-31T00:00
    
    0 讨论(0)
提交回复
热议问题