简体   繁体   English

前一年的同一天(前一年,同一周和星期几)

[英]Same day prevous year (previous year, same week and day of week)

I want to retrieve same day previous year.我想检索前一年的同一天。

eg today is 2019-03-30 that is year 2019, week 26(week of year), day 7 (day of week).例如,今天是2019-03-30 ,即 2019 年,第 26 周(一年中的一周),第 7 天(一周中的某天)。

I need to construct LocalDate which is year 2018, week 26(week of year), day 7 (day of week).我需要构造LocalDate ,它是 2018 年,第 26 周(一年中的一周),第 7 天(一周中的某天)。

I could not find from java.time package which can built LocalDate like this.我无法从java.time包中找到可以像这样构建LocalDate包。

It seems like you want the previous year date with same week of year and day of week as the given date.似乎您希望上一年的日期与给定日期具有相同的年份和星期几。 Below code with give you that result.下面的代码给你那个结果。

LocalDate currentLocalDate = LocalDate.now();
int dayOfWeek = currentLocalDate.getDayOfWeek().getValue();
int weekOfYear = currentLocalDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
LocalDate resultLocalDate = currentLocalDate
    .minusYears(1)
    .with(ChronoField.ALIGNED_WEEK_OF_YEAR, weekOfYear)
    .with(ChronoField.DAY_OF_WEEK, dayOfWeek);

Full Example ( live copy ):完整示例(实时复制):

import java.time.*;
import java.time.format.*;
import java.time.temporal.*;

class Example
{
    private static void showDateInfo(LocalDate ld) {
        int weekOfYear = ld.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
        int dayOfWeek = ld.getDayOfWeek().getValue();
        System.out.println(ld.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is week " + weekOfYear + ", day " + dayOfWeek);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        LocalDate currentLocalDate = LocalDate.of(2019, 6, 30);
        showDateInfo(currentLocalDate);
        int dayOfWeek = currentLocalDate.getDayOfWeek().getValue();
        int weekOfYear = currentLocalDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
        LocalDate resultLocalDate = currentLocalDate
            .minusYears(1)
            .with(ChronoField.ALIGNED_WEEK_OF_YEAR, weekOfYear)
            .with(ChronoField.DAY_OF_WEEK, dayOfWeek);
        showDateInfo(resultLocalDate);
    }
}

Output:输出:

2019-06-30 is week 26, day 7
2018-07-01 is week 26, day 7

I believe that the other answers are close but not quite there yet.我相信其他答案很接近,但还没有完全到位。 As far as I understand, you want to use the week scheme of the default locale, which the other answers don't do.据我了解,您想使用默认语言环境的周方案,而其他答案没有这样做。 My suggestion is:我的建议是:

    WeekFields wf = WeekFields.of(Locale.getDefault());
    LocalDate today = LocalDate.now(ZoneId.of("Africa/Casablanca"));
    int week = today.get(wf.weekOfYear());
    int dow = today.get(wf.dayOfWeek());
    System.out.println("Today is " + today + ", "
            + today.getDayOfWeek() + " of week " + week);

    LocalDate correspondingDayLastYear = today.minusYears(1)
            .with(wf.weekOfYear(), week)
            .with(wf.dayOfWeek(), dow);
    System.out.println("Last year was " + correspondingDayLastYear + ", "
            + correspondingDayLastYear.getDayOfWeek()
            + " of week " + correspondingDayLastYear.get(wf.weekOfYear()));

When running on my computer just now the output was:刚才在我的电脑上运行时,输出是:

 Today is 2019-06-30, SUNDAY of week 26 Last year was 2018-07-01, SUNDAY of week 26

When I set my locale to US I get the same date, but a different week number since American weeks are defined differently:当我将语言环境设置为美国时,我得到相同的日期,但由于美国周的定义不同,因此周数不同:

 Today is 2019-06-30, SUNDAY of week 27 Last year was 2018-07-01, SUNDAY of week 27

I believe that there will also be cases where different locales will give you different dates.我相信也会有不同的语言环境会给你不同的日期的情况。

wf.dayOfWeek() gives you a field that numbers the days from 1 to 7 according to the first day of week in that particular locale. wf.dayOfWeek()为您提供一个字段,该字段根据该特定语言环境中的一周的第一天从 1 到 7 编号。 It's important not just to use withDayOfWeek or equivalent, or you would risk sliding into a different week if not using ISO weeks.重要的是不仅要使用withDayOfWeek或等效的,否则如果不使用 ISO 周,您将面临滑入不同周的风险。

Still my answer will not work always!我的答案仍然不会总是有效! If today is within week 53 of the year, it may very well be that last year didn't have a week 53. Not much we can do about that.如果今天是在一年的第 53 周内,那很可能是去年没有第 53 周。对此我们无能为力。 Another problem we can't solve: In American weeks week 1 starts on January 1. If this is a Sunday, it is the first day for the week, but then week 1 of the previous year started on a Friday or Saturday, so week 1 didn't have any Sunday.另一个我们无法解决的问题:在美国的周中,第 1 周从 1 月 1 日开始。如果这是星期日,则它是该周的第一天,但​​上一年的第 1 周从周五或周六开始,因此周1 没有任何星期天。

If you're looking for an ISO week-year compatible function, this is working for me - so far =].如果您正在寻找 ISO 周年兼容功能,这对我有用 - 到目前为止 =]。

public class FiscalDateUtil {
    
    private static Logger log = LoggerFactory.getLogger(FiscalDateUtil.class);

    static public LocalDate previousYearComparisonDate(LocalDate date) {
    
        final int weekYear = date.get(IsoFields.WEEK_BASED_YEAR);
        final int weekLastYear = weekYear-1;
        
        final DayOfWeek dayOfWeek = date.getDayOfWeek();
        final int weekOfYear = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
        final LocalDate adjustedLastYear = date
                .with(IsoFields.WEEK_BASED_YEAR, weekLastYear)
                .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekOfYear)
                .with(TemporalAdjusters.nextOrSame(dayOfWeek));

        if (log.isTraceEnabled()) {
            log.trace("starting date {}", date.toString());
            log.trace("starting date dow {}", date.getDayOfWeek());
            log.trace("lastYear {}", weekLastYear);
            log.trace("lastYear dow {}", dayOfWeek);
            log.trace("adjustedLastYear {}", adjustedLastYear.toString());
            log.trace("adjustedLastYear dow {}", adjustedLastYear.getDayOfWeek());  
        }
        return adjustedLastYear;
    }

}

You can add the number of days since beginning of year of the current date to the beginning of the year before.您可以将自当前日期的年初以来的天数添加到前一年的年初。

This should do the trick:这应该可以解决问题:

String dateStr = "2019-03-30";
LocalDate date = LocalDate.parse(dateStr);
LocalDate newDate = LocalDate.parse(date.getYear() + "-01-01").plusDays(date.getDayOfYear());
System.out.println(newDate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM