查找指定一周中第一天的特定日期的星期几

时间:2022-10-21 12:54:34

I am implementing a method similar to the VB Weekday function that can give the weekday number given any Day-of-Week as the start for the week.

我正在实现一个类似于VB Weekday函数的方法,它可以给出工作日编号,给出任何一周的星期几作为一周的开始。

For the example of "2010-02-16" (which is on a Tuesday), and a first-day-of-week of Sunday (1), I expect the value 3 as outcome.

对于“2010-02-16”(在星期二)以及星期日(1)的第一天的例子,我期望值3作为结果。

4 个解决方案

#1


This can be done with the help of Calendar class and little calculation.

这可以通过Calendar类和很少的计算来完成。

  1. Parse the Date
  2. 解析日期

  3. Get Calendar Instance and initialize it with parsed Date
  4. 获取日历实例并使用已解析的日期对其进行初始化

  5. Get the day of week number at that time
  6. 获取当时的星期数

  7. Calculate day of week w.r.t. startDay by doing the calculation pointed out by @Markus
  8. 计算星期几w.r.t.通过执行@Markus指出的计算来启动

Below method demonstrates that:

以下方法证明:

public int Weekday(String dateString, int startDay) {
    Date date = null;

    try {
        SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyy-MM-dd");
        date = desiredFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
        return -1;
    }

    Calendar c = Calendar.getInstance();
    c.setTime(date);
    if (startDay == 0) {
        return c.get(Calendar.DAY_OF_WEEK);
    }
    else {
        return (((c.get(Calendar.DAY_OF_WEEK) - startDay + 7) % 7) + 1);
    }
}

Update: Thanks to comment by @Markus

更新:感谢@Markus的评论

#2


Summarizing the answers of JoD. and Asif Mujteba, that should be something like this:

总结了JoD的答案。和Asif Mujteba,这应该是这样的:

import java.time.*;
import java.util.*;

public class SampleClass {

     public static void main(String []args) throws Exception {
        System.out.println(Weekday("2010-02-16", 1));
        System.out.println(Weekday("2015-05-03", 1));
        System.out.println(Weekday("2015-05-04", 1));
        System.out.println(Weekday("2015-05-05", 1));
        System.out.println(Weekday("2015-05-06", 1));
        System.out.println(Weekday("2015-05-07", 1));
        System.out.println(Weekday("2015-05-08", 1));
        System.out.println(Weekday("2015-05-09", 1));
        System.out.println(Weekday("2015-05-10", 1));
     }

    public static int Weekday(String dateString, int startDay) throws Exception {
        LocalDate date = LocalDate.parse(dateString);
        return (((date.getDayOfWeek().ordinal() - startDay + 2) % 7) + 1;
    }
}

This will return:

这将返回:

3
1
2
3
4
5
6
7
1

And thats is the same as DateAndTime.Weekday returns ...

这与DateAndTime.Weekday返回相同......

#3


Below accepts the date provided as string, and formatted in the ISO-8601 extended local date format (e.g. 2010-02-16). The day of Week is using the DayOfWeek Enum. Note however that this depends on Java 8 (standard libraries, not Joda-Time). Use of LocalDate is important to avoid TimeZone and Time issues (partial days).

下面接受以字符串形式提供的日期,并以ISO-8601扩展本地日期格式(例如2010-02-16)格式化。星期几是使用DayOfWeek Enum。但请注意,这取决于Java 8(标准库,而不是Joda-Time)。使用LocalDate对于避免TimeZone和Time问题(部分日期)非常重要。

UPDATE: also provided a static method mimicking the VB version with an integer parameter for the date. All except 0 (System default based on NLS) are accepted.

更新:还提供了一个模拟VB版本的静态方法,其中包含日期的整数参数。除0以外的所有内容(基于NLS的系统默认值)均被接受。

UPDATE #2: Had to modify previous into previousOrSame otherwise we would get 8 instead of 1 as result. The result is expected to be in the range 1-7.

更新#2:必须修改previous到previousOrSame,否则我们会得到8而不是1。结果预计在1-7范围内。

import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.DayOfWeek.*;
import static java.time.temporal.ChronoUnit.*;
import static java.time.temporal.TemporalAdjusters.*;

public class Main {
  public static void main(String[] args) {
    // Thanks to @Markus for the testcase
    System.out.println(getVbWeekday("2010-02-16", 1));
    System.out.println(getVbWeekday("2015-05-03", 1));
    System.out.println(getVbWeekday("2015-05-04", 1));
    System.out.println(getVbWeekday("2015-05-05", 1));
    System.out.println(getVbWeekday("2015-05-06", 1));
    System.out.println(getVbWeekday("2015-05-07", 1));
    System.out.println(getVbWeekday("2015-05-08", 1));
    System.out.println(getVbWeekday("2015-05-09", 1));
    System.out.println(getVbWeekday("2015-05-10", 1));
  }

  public static int getWeekdayNumber(String dateAsString,DayOfWeek firstDayOfWeek) {
    LocalDate d = LocalDate.parse(dateAsString);
     // add 1 because between is exclusive end date.
    return (int)DAYS.between(d.with(previousOrSame(firstDayOfWeek)),d)+1;
  }

  public static int getVbWeekday(String dateAsString,int firstDayOfWeek) {
    return getWeekdayNumber(dateAsString,SATURDAY.plus(firstDayOfWeek));
  }
}

#4


i have implemented below menitoned method in java using jodaTime which will return the difference.

我在java中使用jodaTime实现了menitoned方法,它将返回差异。

public int generateDifference(String dtStr, int dayOfWeek) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    DateTime dt = formatter.parseDateTime(dtStr);
    int day = dt.getDayOfWeek() + 1;
    if (dayOfWeek < day) {
        return 8 - Math.abs(dayOfWeek - day);
    }
    return 2 + Math.abs(dayOfWeek - day);
}

#1


This can be done with the help of Calendar class and little calculation.

这可以通过Calendar类和很少的计算来完成。

  1. Parse the Date
  2. 解析日期

  3. Get Calendar Instance and initialize it with parsed Date
  4. 获取日历实例并使用已解析的日期对其进行初始化

  5. Get the day of week number at that time
  6. 获取当时的星期数

  7. Calculate day of week w.r.t. startDay by doing the calculation pointed out by @Markus
  8. 计算星期几w.r.t.通过执行@Markus指出的计算来启动

Below method demonstrates that:

以下方法证明:

public int Weekday(String dateString, int startDay) {
    Date date = null;

    try {
        SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyy-MM-dd");
        date = desiredFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
        return -1;
    }

    Calendar c = Calendar.getInstance();
    c.setTime(date);
    if (startDay == 0) {
        return c.get(Calendar.DAY_OF_WEEK);
    }
    else {
        return (((c.get(Calendar.DAY_OF_WEEK) - startDay + 7) % 7) + 1);
    }
}

Update: Thanks to comment by @Markus

更新:感谢@Markus的评论

#2


Summarizing the answers of JoD. and Asif Mujteba, that should be something like this:

总结了JoD的答案。和Asif Mujteba,这应该是这样的:

import java.time.*;
import java.util.*;

public class SampleClass {

     public static void main(String []args) throws Exception {
        System.out.println(Weekday("2010-02-16", 1));
        System.out.println(Weekday("2015-05-03", 1));
        System.out.println(Weekday("2015-05-04", 1));
        System.out.println(Weekday("2015-05-05", 1));
        System.out.println(Weekday("2015-05-06", 1));
        System.out.println(Weekday("2015-05-07", 1));
        System.out.println(Weekday("2015-05-08", 1));
        System.out.println(Weekday("2015-05-09", 1));
        System.out.println(Weekday("2015-05-10", 1));
     }

    public static int Weekday(String dateString, int startDay) throws Exception {
        LocalDate date = LocalDate.parse(dateString);
        return (((date.getDayOfWeek().ordinal() - startDay + 2) % 7) + 1;
    }
}

This will return:

这将返回:

3
1
2
3
4
5
6
7
1

And thats is the same as DateAndTime.Weekday returns ...

这与DateAndTime.Weekday返回相同......

#3


Below accepts the date provided as string, and formatted in the ISO-8601 extended local date format (e.g. 2010-02-16). The day of Week is using the DayOfWeek Enum. Note however that this depends on Java 8 (standard libraries, not Joda-Time). Use of LocalDate is important to avoid TimeZone and Time issues (partial days).

下面接受以字符串形式提供的日期,并以ISO-8601扩展本地日期格式(例如2010-02-16)格式化。星期几是使用DayOfWeek Enum。但请注意,这取决于Java 8(标准库,而不是Joda-Time)。使用LocalDate对于避免TimeZone和Time问题(部分日期)非常重要。

UPDATE: also provided a static method mimicking the VB version with an integer parameter for the date. All except 0 (System default based on NLS) are accepted.

更新:还提供了一个模拟VB版本的静态方法,其中包含日期的整数参数。除0以外的所有内容(基于NLS的系统默认值)均被接受。

UPDATE #2: Had to modify previous into previousOrSame otherwise we would get 8 instead of 1 as result. The result is expected to be in the range 1-7.

更新#2:必须修改previous到previousOrSame,否则我们会得到8而不是1。结果预计在1-7范围内。

import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.DayOfWeek.*;
import static java.time.temporal.ChronoUnit.*;
import static java.time.temporal.TemporalAdjusters.*;

public class Main {
  public static void main(String[] args) {
    // Thanks to @Markus for the testcase
    System.out.println(getVbWeekday("2010-02-16", 1));
    System.out.println(getVbWeekday("2015-05-03", 1));
    System.out.println(getVbWeekday("2015-05-04", 1));
    System.out.println(getVbWeekday("2015-05-05", 1));
    System.out.println(getVbWeekday("2015-05-06", 1));
    System.out.println(getVbWeekday("2015-05-07", 1));
    System.out.println(getVbWeekday("2015-05-08", 1));
    System.out.println(getVbWeekday("2015-05-09", 1));
    System.out.println(getVbWeekday("2015-05-10", 1));
  }

  public static int getWeekdayNumber(String dateAsString,DayOfWeek firstDayOfWeek) {
    LocalDate d = LocalDate.parse(dateAsString);
     // add 1 because between is exclusive end date.
    return (int)DAYS.between(d.with(previousOrSame(firstDayOfWeek)),d)+1;
  }

  public static int getVbWeekday(String dateAsString,int firstDayOfWeek) {
    return getWeekdayNumber(dateAsString,SATURDAY.plus(firstDayOfWeek));
  }
}

#4


i have implemented below menitoned method in java using jodaTime which will return the difference.

我在java中使用jodaTime实现了menitoned方法,它将返回差异。

public int generateDifference(String dtStr, int dayOfWeek) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    DateTime dt = formatter.parseDateTime(dtStr);
    int day = dt.getDayOfWeek() + 1;
    if (dayOfWeek < day) {
        return 8 - Math.abs(dayOfWeek - day);
    }
    return 2 + Math.abs(dayOfWeek - day);
}