1

I have a string containing a date in the form

04-Jan-15

and need to get the week number of the year out of it. for the above example week 1(or 2 depending on locale and weekdays in December. never mind that).

I have this:

   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();
    }

This returns

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

Calendar Month:2

Calendar Week:3

I tried (earlier) this

temp.set(year, month, day);

and was still getting wrong results.

Any idea?

Skaros Ilias
  • 1,008
  • 12
  • 40

2 Answers2

1

tl;dr

For culturally-defined weeks…

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.

For standard weeks…

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

You are using troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. Much simpler now to solve your problem.

Parse your input string. Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

String input = "04-Jan-15";

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

Dump to console.

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

input: 04-Jan-15 = 2015-01-04

Week number

Week number is culturally defined. To access week-of-year, you must specify a Locale whose culture you want to use in defining a week.

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

By the way, that input string format is not good. When exchanging date-time values as text, always use ISO 8601 standard formats. These are used by default in java.time when parsing/generating strings.


About java.time

The 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.

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

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The 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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

MONTH and WEEK_OF_YEAR in class Calendar are constants, not the month and week of year of any particular Calendar object.

You use these constants with the get(...) method. The constant indicates which field you want to get. Like this:

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

Also, there's a much easier way to parse a string like 04-Jan-15 into a Date object than doing it manually:

String text = "04-Jan-15";

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

(Why are you first parsing the string manually, then converting it into another format dd/MM/yyyy and then parsing that again? That's much more complicated than necessary).

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • so thats what >Field number for get and set indicating the week number within the current year means on the API. Thanks – Skaros Ilias Apr 08 '15 at 20:57
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 29 '17 at 05:18