简体   繁体   中英

Java Calendar.WEEK_OF_YEAR returns week of the month

/* package whatever; // don't place package name! */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone {

    public static void main (String[] args) throws java.lang.Exception {
        try {
            // your code goes here
            SimpleDateFormat sdf= new SimpleDateFormat("dd-mm-yyyy");
            Calendar cal= Calendar.getInstance();
            String s = "12-12-2014";
            Date dte=sdf.parse(s);
            cal.setTime(dte);

            System.out.println( cal.get(Calendar.WEEK_OF_YEAR)+"");
        } catch (Exception e ) {}
    }
}

Output is 3 .

I am trying to get week of the year from a given date. I referred java docs but the WEEK_OF_YEAR should be in 50 .

Your SimpleDateFormat is wrong, see JavaDoc :

Letter | Date or Time | Component | Presentation | Examples

m | Minute in hour | Number | 30

It should be:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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