从带有月份名称的字符串日期中获取周数

get week number from string date with month name

我有一个包含日期的字符串,格式为

04-Jan-15

并且需要从中获取一年中的周数。 对于上面的示例 week 1(或 2,具体取决于 12 月的语言环境和工作日。没关系)。

我有这个:

   String[] startDate=dates[0].split("-");    
   int month,day,year;
   year=2000+Integer.parseInt(startDate[2]);
   day=Integer.parseInt(startDate[0]);

   switch (startDate[1]){
    case "Jan": 
        {
            month=1;
            break;
        }
........
........
    case "Dec": 
        {
        month=12;
        break;
        }
    }

   Calendar temp=new GregorianCalendar();
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    try {

        Date tempDate = sdf.parse(day+"/"+month+"/"+year);
        System.out.println("DATE:"+tempDate);
        temp.setTime(tempDate);
        System.out.println("Calendar Month:"+temp.MONTH);
        System.out.println("Calendar Week:"+temp.WEEK_OF_YEAR);

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这个returns

DATE:Sun Jan 04 00:00:00 EET 2015

Calendar Month:2

Calendar Week:3

我(早些时候)尝试过这个

temp.set(year, month, day);

并且仍然得到错误的结果。

有什么想法吗?

MONTH 和 class Calendar 中的 WEEK_OF_YEAR 是常数,而不是任何特定 Calendar 对象的月份和年份。

您可以通过 get(...) 方法使用这些常量。该常量指示您要获取哪个字段。像这样:

System.out.println("Calendar Month:" + temp.get(Calendar.MONTH));
System.out.println("Calendar Week:" + temp.get(Calendar.WEEK_OF_YEAR));

此外,还有一种比手动将 04-Jan-15 这样的字符串解析为 Date 对象更简单的方法:

String text = "04-Jan-15";

DateFormat df = new SimpleDateFormat("dd-MMM-yy", Locale.US);
Date date = df.parse(text);

(为什么要先手动解析字符串,然后将其转换为另一种格式dd/MM/yyyy,然后再次解析?这比必要的要复杂得多)。

tl;博士

文化定义的周……

LocalDate.parse( 
    "04-Jan-15" , 
    DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US )
).get( 
    WeekFields.of( Locale.FRANCE ).weekOfWeekBasedYear( ) 
)  // Gets week number for a culturally-defined week-of-year.

标准周……

LocalDate.parse( 
    "04-Jan-15" , 
    DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US )
).get( 
    IsoFields.WEEK_OF_WEEK_BASED_YEAR 
)  // Gets standard ISO 8601 week number.

java.time

您使用的是麻烦的旧日期时间 classes,现在已成为遗留问题,完全被 java.time classes 取代。现在解决你的问题就简单多了。

解析您的输入字符串。指定 Locale 以确定 (a) 翻译日名、月名等的人类语言,以及 (b) 决定缩写、大写、标点符号、分隔符等问题的文化规范。

String input = "04-Jan-15";

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US );
LocalDate ld = LocalDate.parse( input , f );

转储到控制台。

System.out.println( "input: " + input + " = " + ld );

输入:2015 年 1 月 4 日 = 2015-01-04

周数

周数由文化定义。要访问一年中的一周,您必须指定 Locale 您要在定义一周时使用其文化。

Locale locale = Locale.FRANCE;
WeekFields fields = WeekFields.of( locale );
TemporalField field = fields.weekOfWeekBasedYear( );
int weekNumber = ld.get( WeekFields.of( Locale.FRANCE ).weekOfWeekBasedYear( ) ); // Gets week number for a culturally-defined week-of-year.

ISO 8601 defines standard week numbers where week # 1 contains the first Thursday of the year, and begins on a Monday. The java.time class offer this approach built-in in the IsoFields class.

int weekNumber = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR )  // Gets standard ISO 8601 week number.

ISO 8601

顺便说一句,输入的字符串格式不好。将日期时间值作为文本交换时,始终使用 ISO 8601 标准格式。这些在 java.time 中默认使用 parsing/generating 字符串。


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

从哪里获得java.time classes?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.