How to get first day of a given week number in Java

前端 未结 7 634
独厮守ぢ
独厮守ぢ 2020-12-01 12:38

Let me explain myself. By knowing the week number and the year of a date:

Date curr = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(curr);
i         


        
相关标签:
7条回答
  • 2020-12-01 13:16

    Here's some quick and dirty code to do this. This code creates a calendar object with the date of the current day, calculates the current day of the week, and subtracts the day of the week so you're on the first one (Sunday). Although I'm using DAY_OF_YEAR it goes across years fine (on 1/2/10 it'll return 12/27/09 which is right).

    import java.text.Format;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    
    
    public class DOW {
    
        public static void main(String[] args) {
            DOW dow = new DOW();
            dow.doIt();
            System.exit(0);
        }
    
        private void doIt() {
            Date curr = new Date(); 
            Calendar cal = Calendar.getInstance(); 
            cal.setTime(curr); 
            int currentDOW = cal.get(Calendar.DAY_OF_WEEK);
            cal.add(Calendar.DAY_OF_YEAR, (currentDOW * -1)+1);
    
            Format formatter = new SimpleDateFormat("MM/dd/yy");
            System.out.println("First day of week="+formatter.format(cal.getTime()));
        }
    }
    
    0 讨论(0)
提交回复
热议问题