In a recent OA, I need to determine whether two dates are the same week, and according to a given date, the dates of the Monday and Friday that belong to the week.
When I finished this task, I found that calendar is really a powerful class.
Below gives the source code, for the brothers to refer to correct.
/*
* Date Created 2005-3-30
Package Com.infoearth;
Import Java.sql.Timestamp;
Import Java.text.SimpleDateFormat;
Import java.util.*;
/**
* @ Li Chunlei
*
public class Manageweek {
Determine whether two dates are in the same week
Boolean issameweekdates (Date date1, date date2) {
Calendar Cal1 = Calendar.getinstance ();
Calendar Cal2 = Calendar.getinstance ();
Cal1.settime (date1);
Cal2.settime (DATE2);
int subyear = Cal1.get (calendar.year)-Cal2.get (calendar.year);
if (0 = subyear) {
if (Cal1.get (calendar.week_of_year) = = Cal2.get (calendar.week_of_year))
return true;
}
else if (1 = = Subyear && = Cal2.get (calendar.month)) {
If the last week of December spans the first week of the next year, the last week will be the first week of the coming year.
if (Cal1.get (calendar.week_of_year) = = Cal2.get (calendar.week_of_year))
return true;
}
else if ( -1 = = Subyear && = Cal1.get (calendar.month)) {
if (Cal1.get (calendar.week_of_year) = = Cal2.get (calendar.week_of_year))
return true;
}
return false;
}
Generate a weekly sequence
public static String Getseqweek () {
Calendar C = calendar.getinstance (Locale.china);
String week = integer.tostring (C.get (calendar.week_of_year));
if (Week.length () ==1) week = "0" + week;
String year = integer.tostring (C.get (calendar.year));
return year+week;
}
Get the Monday date
public static String Getmonday (date date) {
Calendar C = calendar.getinstance ();
C.settime (date);
C.set (Calendar.day_of_week,calendar.monday);
return new SimpleDateFormat ("Yyyy-mm-dd"). Format (C.gettime ());
}
Get the Friday date
public static String Getfriday (date date) {
Calendar C = calendar.getinstance ();
C.settime (date);
C.set (Calendar.day_of_week,calendar.friday);
return new SimpleDateFormat ("Yyyy-mm-dd"). Format (C.gettime ());
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.