获取星期的开始日期(可配置的开始星期几) [英] Get starting date of week(configurable starting day of week)

查看:153
本文介绍了获取星期的开始日期(可配置的开始星期几)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有当前的日期,以及一个常数,它告诉星期从哪一天开始。我想根据该常数得到一周的开始日期。如果我将一周的第一天硬编码到星期一(或任何东西),那么这很简单。但是一周的第一天不断变化。因此,每次要更改第一天时,我都不想更改代码。

I have current date, and a constant which tells from which day the week starts. I want to get the start date of the week based on that constant. If I hardcode the first day of week to Monday(or anything), then it is simple. But the first day of the week keeps changing. So I don't want to change the code, every time the first day is to be changed.

这是我尝试使用java的日历:

This is what I have tried with java's Calendar:

public static Date getLastWeekdayDate()
{
    Calendar calendar = new GregorianCalendar();
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    int daysToSubtractFromCurrentDate = 0;

    switch (dayOfWeek)
    {
    case Calendar.WEDNESDAY:
        daysToSubtractFromCurrentDate = 4;
        break;

    case Calendar.THURSDAY:
        daysToSubtractFromCurrentDate = 5;
        break;

    case Calendar.FRIDAY:
        daysToSubtractFromCurrentDate = 6;
        break;

    case Calendar.SATURDAY:
        daysToSubtractFromCurrentDate = 0;
        break;

    case Calendar.SUNDAY:
        daysToSubtractFromCurrentDate = 1;
        break;

    case Calendar.MONDAY:
        daysToSubtractFromCurrentDate = 2;
        break;

    case Calendar.TUESDAY:
        daysToSubtractFromCurrentDate = 3;
        break;
    }

    calendar.add(Calendar.DATE, -daysToSubtractFromCurrentDate);
    calendar.set(Calendar.AM_PM, Calendar.AM);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

我想得到一周的开始日期。上述函数返回一周的第一天,并将周开始日硬编码为星期六。每当超出一周开始日的要求发生变化时,我必须更改代码。

I want to get the starting date of the week. The above function returns the first day of the week, and the week start day is hardcoded to Saturday. Whenever the requirement aboout the start day of the week changes, I have to change the code.

推荐答案

我使用了以下方法:

/** 1 = Sunday, 2 = Monday, 3 = Tuesday, 4 = Wednesday, 5 = Thursday,
* 6 = Friday, 7 = Saturday
*/
public static Date getFirstDayOfWeekDate(int firstDay)
{
    // Calculate the date of the first day of the week

    // First get the today's date
    Calendar c = new GregorianCalendar();

    // Now set the day of week to the first day of week
    while (c.get(Calendar.DAY_OF_WEEK) != firstDay)
    {
        c.add(Calendar.DAY_OF_MONTH, -1);
    }

    return c.getTime();
}

这篇关于获取星期的开始日期(可配置的开始星期几)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆