下面列出了java.util.GregorianCalendar#clone ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Constructor
*
* @param date day counter date
* @param isStartDay true first day counter
* false follow up day counter
*/
DayCounter(final GregorianCalendar date, final boolean isStartDay) {
// store internal copy of creation date
this.date = (GregorianCalendar) date.clone();
// initialize the array with '0'- values to current hour (if it is not the
// first monitored day) and the rest with default values ('-1')
int hour = date.get(Calendar.HOUR_OF_DAY);
for (int i = 0; i < DayCounter.HOURS; i++) {
if (i < hour) {
if (isStartDay) {
counters[i] = -1L;
} else {
counters[i] = 0L;
}
} else {
counters[i] = -1L;
}
}
// set the array element of the current hour to '0'
counters[hour] = 0L;
}
/**
* java.util.GregorianCalendar#clone()
*/
public void test_clone() {
// Regression for HARMONY-498
GregorianCalendar gCalend = new GregorianCalendar();
gCalend.set(Calendar.MILLISECOND, 0);
int dayOfMonth = gCalend.get(Calendar.DAY_OF_MONTH);
// create clone object and change date
GregorianCalendar gCalendClone = (GregorianCalendar) gCalend.clone();
gCalendClone.add(Calendar.DATE, 1);
assertEquals("Before", dayOfMonth, gCalend.get(Calendar.DAY_OF_MONTH));
gCalend.set(Calendar.MILLISECOND, 0);//changes nothing
assertEquals("After", dayOfMonth, gCalend.get(Calendar.DAY_OF_MONTH));
}
/**
* Find the date on or before which objects expire based on the given date and the
* retention age specified in this object. The given date is cloned and then adjusted
* downward by the units and value in this RetentionAge.
*
* @param relativeDate Reference date.
* @return The date relative to the given one at which objects should be considered
* expired based on this RetentionAge.
*/
public GregorianCalendar getExpiredDate(GregorianCalendar relativeDate) {
// Get today's date and adjust by the specified age.
GregorianCalendar expiredDate = (GregorianCalendar)relativeDate.clone();
switch (m_units) {
case DAYS:
expiredDate.add(Calendar.DAY_OF_MONTH, -m_value);
break;
case MONTHS:
expiredDate.add(Calendar.MONTH, -m_value);
break;
case YEARS:
expiredDate.add(Calendar.YEAR, -m_value);
break;
default:
// New value we forgot to add here?
throw new AssertionError("Unknown RetentionUnits: " + m_units);
}
return expiredDate;
}
public static void main(String[] args)
{
GregorianCalendar cal1 = new GregorianCalendar() ;
GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ;
printdate(cal1, "cal1: ") ;
printdate(cal2, "cal2 - cloned(): ") ;
cal1.add(DAY_OF_MONTH, 1) ;
printdate(cal1, "cal1 after adding 1 day: ") ;
printdate(cal2, "cal2 should be unmodified: ") ;
if (cal1.get(DAY_OF_MONTH) == cal2.get(DAY_OF_MONTH)) {
throw new RuntimeException("cloned GregorianCalendar modified");
}
}
public static void main(String[] args)
{
GregorianCalendar cal1 = new GregorianCalendar() ;
GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ;
printdate(cal1, "cal1: ") ;
printdate(cal2, "cal2 - cloned(): ") ;
cal1.add(DAY_OF_MONTH, 1) ;
printdate(cal1, "cal1 after adding 1 day: ") ;
printdate(cal2, "cal2 should be unmodified: ") ;
if (cal1.get(DAY_OF_MONTH) == cal2.get(DAY_OF_MONTH)) {
throw new RuntimeException("cloned GregorianCalendar modified");
}
}
public static void main(String[] args)
{
GregorianCalendar cal1 = new GregorianCalendar() ;
GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ;
printdate(cal1, "cal1: ") ;
printdate(cal2, "cal2 - cloned(): ") ;
cal1.add(DAY_OF_MONTH, 1) ;
printdate(cal1, "cal1 after adding 1 day: ") ;
printdate(cal2, "cal2 should be unmodified: ") ;
if (cal1.get(DAY_OF_MONTH) == cal2.get(DAY_OF_MONTH)) {
throw new RuntimeException("cloned GregorianCalendar modified");
}
}
public void setAlarm() {
// UPDATE: 2017/8/24 更新 时间段自定义
current = Calendar.getInstance();
nightThemeStart = new GregorianCalendar(
current.get(Calendar.YEAR),
current.get(Calendar.MONTH),
current.get(Calendar.DAY_OF_MONTH),
22, 30); // 22:30 切换到夜间模式
nightThemeEnd = (Calendar) nightThemeStart.clone();
nightThemeEnd.add(Calendar.DAY_OF_MONTH, 1); // 后一天
nightThemeEnd.set(Calendar.HOUR_OF_DAY, 7); // 07:00 切换到白天模式
nightThemeEnd.set(Calendar.MINUTE, 0);
checkTheme();
isSet = true;
Intent intentS = new Intent();
Intent intentE = new Intent();
intentS.setAction(BroadcastManager.FILTER_APP_THEME_CHANGE_AUTOMATIC);
intentS.putExtra(BroadcastManager.APP_THEME_CHANGE_AUTOMATIC_TOKEN,
BroadcastManager.APP_THEME_CHANGE_AUTOMATIC_DARK);
intentE.setAction(BroadcastManager.FILTER_APP_THEME_CHANGE_AUTOMATIC);
intentE.putExtra(BroadcastManager.APP_THEME_CHANGE_AUTOMATIC_TOKEN,
BroadcastManager.APP_THEME_CHANGE_AUTOMATIC_WHITE);
piS = PendingIntent.getBroadcast(context, 0, intentS, 0);
piE = PendingIntent.getBroadcast(context, 1, intentE, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, nightThemeStart.getTimeInMillis(), piS);
alarmManager.set(AlarmManager.RTC_WAKEUP, nightThemeEnd.getTimeInMillis(), piE);
}
public static void main(String[] args)
{
GregorianCalendar cal1 = new GregorianCalendar() ;
GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ;
printdate(cal1, "cal1: ") ;
printdate(cal2, "cal2 - cloned(): ") ;
cal1.add(DAY_OF_MONTH, 1) ;
printdate(cal1, "cal1 after adding 1 day: ") ;
printdate(cal2, "cal2 should be unmodified: ") ;
if (cal1.get(DAY_OF_MONTH) == cal2.get(DAY_OF_MONTH)) {
throw new RuntimeException("cloned GregorianCalendar modified");
}
}
/**
* GregorianCalendar.equals() ignores cutover date
*/
public void Test4141665() {
GregorianCalendar cal = new GregorianCalendar();
GregorianCalendar cal2 = (GregorianCalendar) cal.clone();
Date cut = cal.getGregorianChange();
Date cut2 = new Date(cut.getTime() + 100 * 24 * 60 * 60 * 1000L); // 100 days later
if (!cal.equals(cal2)) {
errln("Cloned GregorianCalendars not equal");
}
cal2.setGregorianChange(cut2);
if (cal.equals(cal2)) {
errln("GregorianCalendar.equals() ignores cutover");
}
}
public static void main(String[] args)
{
GregorianCalendar cal1 = new GregorianCalendar() ;
GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ;
printdate(cal1, "cal1: ") ;
printdate(cal2, "cal2 - cloned(): ") ;
cal1.add(DAY_OF_MONTH, 1) ;
printdate(cal1, "cal1 after adding 1 day: ") ;
printdate(cal2, "cal2 should be unmodified: ") ;
if (cal1.get(DAY_OF_MONTH) == cal2.get(DAY_OF_MONTH)) {
throw new RuntimeException("cloned GregorianCalendar modified");
}
}
public void initCalendarAdapter(GregorianCalendar monthCalendar,
onMFCalendarViewListener calendarListener){
CalendarAdapter.dayString = new ArrayList<String>();
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
adaptersetDate(selectedDate, calendarListener);
refreshDays();
}
public void refreshDays() {
// clear items
items.clear();
dayString.clear();
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
/**
* Calendar instance for getting a complete gridview including the three
* month's (previous,current,next) dates.
*/
pmonthmaxset = (GregorianCalendar) pmonth.clone();
/**
* setting the start date as previous month's required date.
*/
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
dayString.add(itemvalue);
}
}
/**
* Truncate the given GregorianCalendar date to the nearest week. This is done by
* cloning it and rounding the value down to the closest Monday. If the given date
* already occurs on a Monday, a copy of the same date is returned.
*
* @param date A GregorianCalendar object.
* @return A copy of the same value, truncated to the nearest Monday.
*/
public static GregorianCalendar truncateToWeek(GregorianCalendar date) {
// Round the date down to the MONDAY of the same week.
GregorianCalendar result = (GregorianCalendar)date.clone();
switch (result.get(Calendar.DAY_OF_WEEK)) {
case Calendar.TUESDAY: result.add(Calendar.DAY_OF_MONTH, -1); break;
case Calendar.WEDNESDAY: result.add(Calendar.DAY_OF_MONTH, -2); break;
case Calendar.THURSDAY: result.add(Calendar.DAY_OF_MONTH, -3); break;
case Calendar.FRIDAY: result.add(Calendar.DAY_OF_MONTH, -4); break;
case Calendar.SATURDAY: result.add(Calendar.DAY_OF_MONTH, -5); break;
case Calendar.SUNDAY: result.add(Calendar.DAY_OF_MONTH, -6); break;
default: break;
}
return result;
}
public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
CalendarAdapter.dayString = new ArrayList<String>();
Locale.setDefault(Locale.US);
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
mContext = c;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public void refreshDays() {
// clear items
items.clear();
dayString.clear();
Locale.setDefault(Locale.US);
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
/**
* Calendar instance for getting a complete gridview including the three
* month's (previous,current,next) dates.
*/
pmonthmaxset = (GregorianCalendar) pmonth.clone();
/**
* setting the start date as previous month's required date.
*/
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
dayString.add(itemvalue);
}
}
DayChooser(DateChooser dc_, GregorianCalendar date, char[] days) {
dc = dc_;
setLayout(new GridLayout(7, 7));
for(int i = 0; i < days.length; i++)
add(new Label("" + days[i], Label.CENTER));
Calendar tmp = (Calendar)date.clone();
tmp.set(Calendar.DAY_OF_MONTH, 1);
int skip = tmp.get(Calendar.DAY_OF_WEEK) - 1;
for(int i = 0; i < skip; i++)
add(new Component() {});
int count = days(date);
for(int i = 1; i <= count; i++) {
b_days[i] = new Button("" + i);
b_days[i].addActionListener(this);
add(b_days[i]);
}
skip = 49 - getComponentCount();
for(int i = 0; i < skip; i++)
add(new Component() {});
select(date.get(Calendar.DAY_OF_MONTH));
}
/**
* Calendar and GregorianCalendar hashCode() methods need improvement.
* Calendar needs a good implementation that subclasses can override,
* and GregorianCalendar should use that implementation.
*/
public void Test4136399() {
/* Note: This test is actually more strict than it has to be.
* Technically, there is no requirement that unequal objects have
* unequal hashes. We only require equal objects to have equal hashes.
* It is desirable for unequal objects to have distributed hashes, but
* there is no hard requirement here.
*
* In this test we make assumptions about certain attributes of calendar
* objects getting represented in the hash, which need not always be the
* case (although it does work currently with the given test). */
Calendar a = Calendar.getInstance();
Calendar b = (Calendar) a.clone();
if (a.hashCode() != b.hashCode()) {
errln("Calendar hash code unequal for cloned objects");
}
b.setMinimalDaysInFirstWeek(7 - a.getMinimalDaysInFirstWeek());
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores minimal days in first week");
}
b.setMinimalDaysInFirstWeek(a.getMinimalDaysInFirstWeek());
b.setFirstDayOfWeek((a.getFirstDayOfWeek() % 7) + 1); // Next day
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores first day of week");
}
b.setFirstDayOfWeek(a.getFirstDayOfWeek());
b.setLenient(!a.isLenient());
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores lenient setting");
}
b.setLenient(a.isLenient());
// Assume getTimeZone() returns a reference, not a clone
// of a reference -- this is true as of this writing
b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset() + 60 * 60 * 1000);
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores zone");
}
b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset());
GregorianCalendar c = new GregorianCalendar();
GregorianCalendar d = (GregorianCalendar) c.clone();
if (c.hashCode() != d.hashCode()) {
errln("GregorianCalendar hash code unequal for clones objects");
}
Date cutover = c.getGregorianChange();
d.setGregorianChange(new Date(cutover.getTime() + 24 * 60 * 60 * 1000));
if (c.hashCode() == d.hashCode()) {
errln("GregorianCalendar hash code ignores cutover");
}
}
public void handleActivityNotif(byte[] value) {
boolean firstChunk = activityStruct == null;
if (firstChunk) {
activityStruct = new ActivityStruct();
}
if (value.length == 11) {
// byte 0 is the data type: 1 means that each minute is represented by a triplet of bytes
int dataType = value[0];
// byte 1 to 6 represent a timestamp
GregorianCalendar timestamp = parseTimestamp(value, 1);
// counter of all data held by the band
int totalDataToRead = (value[7] & 0xff) | ((value[8] & 0xff) << 8);
totalDataToRead *= (dataType == 1) ? 3 : 1;
// counter of this data block
int dataUntilNextHeader = (value[9] & 0xff) | ((value[10] & 0xff) << 8);
dataUntilNextHeader *= (dataType == 1) ? 3 : 1;
// there is a total of totalDataToRead that will come in chunks (3 bytes per minute if dataType == 1),
// these chunks are usually 20 bytes long and grouped in blocks
// after dataUntilNextHeader bytes we will get a new packet of 11 bytes that should be parsed
// as we just did
if (firstChunk && dataUntilNextHeader != 0) {
String message = String.format("About to transfer %1$s of data starting from %2$s",
(totalDataToRead / 3),
DateFormat.getDateTimeInstance().format(timestamp.getTime()));
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
Log.i(TAG, "total data to read: " + totalDataToRead + " len: " + (totalDataToRead / 3) + " minute(s)");
Log.i(TAG, "data to read until next header: " + dataUntilNextHeader + " len: " + (dataUntilNextHeader / 3) + " minute(s)");
Log.i(TAG, "TIMESTAMP: " + DateFormat.getDateTimeInstance().format(timestamp.getTime()) + " magic byte: " + dataUntilNextHeader);
activityStruct.activityDataRemainingBytes = activityStruct.activityDataUntilNextHeader = dataUntilNextHeader;
activityStruct.activityDataTimestampToAck = (GregorianCalendar) timestamp.clone();
activityStruct.activityDataTimestampProgress = timestamp;
} else {
bufferActivityData(value);
}
Log.e(TAG, "activity data: length: " + value.length + ", remaining bytes: " + activityStruct.activityDataRemainingBytes);
if (activityStruct.activityDataRemainingBytes == 0) {
sendAckDataTransfer(activityStruct.activityDataTimestampToAck, activityStruct.activityDataUntilNextHeader);
}
}
public void handleActivityNotif(byte[] value) {
boolean firstChunk = activityStruct == null;
if (firstChunk) {
activityStruct = new ActivityStruct();
}
if (value.length == 11) {
// byte 0 is the data type: 1 means that each minute is represented by a triplet of bytes
int dataType = value[0];
// byte 1 to 6 represent a timestamp
GregorianCalendar timestamp = parseTimestamp(value, 1);
// counter of all data held by the band
int totalDataToRead = (value[7] & 0xff) | ((value[8] & 0xff) << 8);
totalDataToRead *= (dataType == 1) ? 3 : 1;
// counter of this data block
int dataUntilNextHeader = (value[9] & 0xff) | ((value[10] & 0xff) << 8);
dataUntilNextHeader *= (dataType == 1) ? 3 : 1;
// there is a total of totalDataToRead that will come in chunks (3 bytes per minute if dataType == 1),
// these chunks are usually 20 bytes long and grouped in blocks
// after dataUntilNextHeader bytes we will get a new packet of 11 bytes that should be parsed
// as we just did
if (firstChunk && dataUntilNextHeader != 0) {
String message = String.format("About to transfer %1$s of data starting from %2$s",
(totalDataToRead / 3),
DateFormat.getDateTimeInstance().format(timestamp.getTime()));
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
Log.i(TAG, "total data to read: " + totalDataToRead + " len: " + (totalDataToRead / 3) + " minute(s)");
Log.i(TAG, "data to read until next header: " + dataUntilNextHeader + " len: " + (dataUntilNextHeader / 3) + " minute(s)");
Log.i(TAG, "TIMESTAMP: " + DateFormat.getDateTimeInstance().format(timestamp.getTime()) + " magic byte: " + dataUntilNextHeader);
activityStruct.activityDataRemainingBytes = activityStruct.activityDataUntilNextHeader = dataUntilNextHeader;
activityStruct.activityDataTimestampToAck = (GregorianCalendar) timestamp.clone();
activityStruct.activityDataTimestampProgress = timestamp;
} else {
bufferActivityData(value);
}
Log.e(TAG, "activity data: length: " + value.length + ", remaining bytes: " + activityStruct.activityDataRemainingBytes);
if (activityStruct.activityDataRemainingBytes == 0) {
sendAckDataTransfer(activityStruct.activityDataTimestampToAck, activityStruct.activityDataUntilNextHeader);
}
}
/**
* Calculates the next scheduled time after the given time. Algorithm idea:<br> -
* start with biggest time unit (i.e. year) of the given time <br> - if the
* time unit is valid (e.g. the time unit matches the <br>
* scheduled time, this is implicitly true if the time in the <br>
* schedule was omitted) *and* there exists a valid smaller time <br>
* unit, *then* return this time unit <br> - do this recursively for all
* time units <br> - month needs to be special cased because of dayOfWeek
*
* @param time
* Time after which next scheduled time should be returned.
* @return The next scheduled time after 'time'.
* @throws ImplementationException
* Almost any kind of error.
*/
public GregorianCalendar nextScheduledTime(final GregorianCalendar time) throws ImplementationExceptionResponse {
GregorianCalendar nextSchedule = (GregorianCalendar) time.clone();
// look at year
while (!monthMadeValid(nextSchedule)) {
nextSchedule.roll(YEAR, true);
setFieldsToMinimum(nextSchedule, MONTH);
}
return nextSchedule;
}