Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

java - Retrieve current week's Monday's date

We have a utility that will run any day between Monday - Friday. It will update some number of files inside a Content Management Tool. The last modified date associated with that file should be, that week's monday's date. I wrote the following program to retrieve current week's monday's date. But I am still not sure whether this would work for all scenarios. Has anyone got a better solution ?

Calendar c = Calendar.getInstance();
c.setTime(new Date());
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
int mondayNo = c.get(Calendar.DAY_OF_MONTH)-c.get(Calendar.DAY_OF_WEEK)+2;
c.set(Calendar.DAY_OF_MONTH,mondayNo);
System.out.println("Date "+c.getTime());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would strongly recommend using Joda Time instead (for all your date/time work, not just this):

// TODO: Consider time zones, calendars etc
LocalDate now = new LocalDate();
LocalDate monday = now.withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(monday);

Note that as you've used Monday here, which is the first day of the week in Joda Time, this will always return an earlier day (or the same day). If you chosen Wednesday (for example), then it would advance to Wednesday from Monday or Tuesday. You can always add or subtract a week if you need "the next Wednesday" or "the previous Wednesday".

EDIT: If you really want to use java.util.Date/Calendar, you can use:

Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());

You can use Calendar.setFirstDayOfWeek to indicate whether a week is Monday-Sunday or Sunday-Saturday; I believe setting the day of the week will stay within the current week - but test it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...