簡體   English   中英

從android中的周數和年份獲取周開始和結束日期

[英]get week start and end date from week number & year in android

我希望獲得一周的開始日期和結束日期,以及傳入方法的一周數字。 例如,如果我將周數作為51 ,將年份作為2011 ,則應將我的開始日期定為18 Dec 2011 ,結束日期為24 Dec 2011

有沒有什么方法可以幫助我實現這一目標?

您可以使用以下方法獲取一周的第一個日期和結束日期

 void getStartEndOFWeek(int enterWeek, int enterYear){
//enterWeek is week number
//enterYear is year
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.WEEK_OF_YEAR, enterWeek);
        calendar.set(Calendar.YEAR, enterYear);

        SimpleDateFormat formatter = new SimpleDateFormat("ddMMM yyyy"); // PST`
        Date startDate = calendar.getTime();
        String startDateInStr = formatter.format(startDate);
        System.out.println("...date..."+startDateInStr);

        calendar.add(Calendar.DATE, 6);
        Date enddate = calendar.getTime();
        String endDaString = formatter.format(enddate);
        System.out.println("...date..."+endDaString);
    }

您需要使用java.util.Calendar類。 您可以設置年Calendar.YEAR和一年的周Calendar.WEEK_OF_YEAR使用public void set(int field, int value)的方法。

只要正確設置了語言環境,您甚至可以使用setFirstDayOfWeek來更改一周的第一天。 您的日歷實例所代表的日期將是您的開始日期。 只需為您的結束日期添加6天。

Calendar calendar = new GregorianCalendar();
// Clear the calendar since the default is the current time
calendar.clear(); 
// Directly set year and week of year
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.WEEK_OF_YEAR, 51);
// Start date for the week
Date startDate = calendar.getTime();
// Add 6 days to reach the last day of the current week
calendar.add(Calendar.DAY_OF_YEAR, 6);
// End date for the week
Date endDate = calendar.getTime();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM