How to detect if a date is within this or next week in java?

前端 未结 5 2054
半阙折子戏
半阙折子戏 2021-02-15 02:05

If I have a date of an event, such as 2011-01-03, how to detect if it is within this or next week in java ? Any sample code ?

Edit :

I thought it was a simple qu

5条回答
  •  伪装坚强ぢ
    2021-02-15 02:44

    How about this :

    Calendar c=Calendar.getInstance();
    c.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
    c.set(Calendar.HOUR_OF_DAY,0);
    c.set(Calendar.MINUTE,0);
    c.set(Calendar.SECOND,0);
    DateFormat df=new SimpleDateFormat("EEE yyyy/MM/dd HH:mm:ss");
    System.out.println(df.format(c.getTime()));      // This past Sunday [ May include today ]
    c.add(Calendar.DATE,7);
    System.out.println(df.format(c.getTime()));      // Next Sunday
    c.add(Calendar.DATE,7);
    System.out.println(df.format(c.getTime()));      // Sunday after next
    

    The result :

    Sun 2010/12/26 00:00:00
    Sun 2011/01/02 00:00:00
    Sun 2011/01/09 00:00:00
    

    Any day between the first two is this week, anything between the last two is next week.

提交回复
热议问题