下面列出了java.util.Calendar#JANUARY 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the time elapsed so far this month and the last numMonths months in milliseconds.
*
* @param numMonths Additional number of months prior to the current month to calculate.
* @return Time elapsed this month and the last numMonths months in milliseconds.
*/
public long getElapsedMonths(int numMonths) {
// Today + rest of this month
long elapsed = getElapsedMonth();
// Previous numMonths months
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
for (int i = 0; i < numMonths; i++) {
month--;
if (month < Calendar.JANUARY) {
month = Calendar.DECEMBER;
year--;
}
elapsed += getDaysInMonth(year, month) * MS_PER_DAY;
}
return elapsed;
}
public static Integer season(Date date) throws Exception {
Calendar cal = DateUtils.toCalendar(date);
switch (cal.get(Calendar.MONTH)) {
case Calendar.JANUARY:
case Calendar.FEBRUARY:
case Calendar.MARCH:
return 1;
case Calendar.APRIL:
case Calendar.MAY:
case Calendar.JUNE:
return 2;
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.SEPTEMBER:
return 3;
case Calendar.OCTOBER:
case Calendar.NOVEMBER:
case Calendar.DECEMBER:
default:
return 4;
}
}
/**
* Set focus of calendar-component to certain date. Calculate correct week-of-year and year for certain date.
*
* @param gotoDate
*/
public void setDate(final Date gotoDate) {
final Calendar cal = CalendarUtils.createCalendarInstance(getTranslator().getLocale());
cal.setTime(gotoDate);
int weekYear = cal.get(Calendar.YEAR);
final int week = cal.get(Calendar.WEEK_OF_YEAR);
if (week == 1) {
// Week 1 is a special case: the date could be the last days of december, but the week is still counted as week one of the next year. Use the next year in
// this case to match the week number.
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER) {
weekYear++;
}
} else if (week >= 52) {
// Opposite check: date could be first days of january, but the week is still counted as the last week of the passed year. Use the last year in this case to
// match the week number.
if (cal.get(Calendar.MONTH) == Calendar.JANUARY) {
weekYear--;
}
}
setFocus(weekYear, week);
}
/**
* Parse a month value to an offset from Calendar.JANUARY. The source month
* value can be numeric (1-12), a shortform or longform month name as
* defined in DateFormatSymbols.
*
* @param month as a string.
* @param offset the offset of original timestamp where month started, for
* error reporting.
* @return month as an offset from Calendar.JANUARY.
* @see DateFormatSymbols
* @throws ParseException if the source could not be parsed.
*/
int parseMonth(String month, int offset) throws ParseException {
if (month.length() < 3) {
return (parseNumber(month, offset, "month", 1, 12) - 1) + Calendar.JANUARY;
}
String months[] = getDateFormatSymbols().getMonths();
for (int i = 0; i < months.length; i++) {
if (month.equalsIgnoreCase(months[i])) {
return i + Calendar.JANUARY;
}
}
months = getDateFormatSymbols().getShortMonths();
for (int i = 0; i < months.length; i++) {
if (month.equalsIgnoreCase(months[i])) {
return i + Calendar.JANUARY;
}
}
return throwInvalid("month", offset);
}
public static int getDaysInMonth(int month, int year) {
switch (month) {
case Calendar.JANUARY:
case Calendar.MARCH:
case Calendar.MAY:
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.OCTOBER:
case Calendar.DECEMBER:
return 31;
case Calendar.APRIL:
case Calendar.JUNE:
case Calendar.SEPTEMBER:
case Calendar.NOVEMBER:
return 30;
case Calendar.FEBRUARY:
return (year % 4 == 0) ? 29 : 28;
default:
throw new IllegalArgumentException("Invalid Month");
}
}
/**
* Creates a time period for the week in which the specified date/time
* falls, calculated relative to the specified time zone.
*
* @param time the date/time (<code>null</code> not permitted).
* @param zone the time zone (<code>null</code> not permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @since 1.0.7
*/
public Week(Date time, TimeZone zone, Locale locale) {
if (time == null) {
throw new IllegalArgumentException("Null 'time' argument.");
}
if (zone == null) {
throw new IllegalArgumentException("Null 'zone' argument.");
}
if (locale == null) {
throw new IllegalArgumentException("Null 'locale' argument.");
}
Calendar calendar = Calendar.getInstance(zone, locale);
calendar.setTime(time);
// sometimes the last few days of the year are considered to fall in
// the *first* week of the following year. Refer to the Javadocs for
// GregorianCalendar.
int tempWeek = calendar.get(Calendar.WEEK_OF_YEAR);
if (tempWeek == 1
&& calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
this.week = 1;
this.year = (short) (calendar.get(Calendar.YEAR) + 1);
}
else {
this.week = (byte) Math.min(tempWeek, LAST_WEEK_IN_YEAR);
int yyyy = calendar.get(Calendar.YEAR);
// alternatively, sometimes the first few days of the year are
// considered to fall in the *last* week of the previous year...
if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
&& this.week >= 52) {
yyyy--;
}
this.year = (short) yyyy;
}
peg(calendar);
}
@Test
public void testInterruptedPeriodWithUser1EndOfJanuary() throws Exception {
final int testMonth = Calendar.JANUARY;
final int testDay = 31;
final BigDecimal etalonPrice = new BigDecimal("746.37");
testInterruptedPeriod(testMonth, testDay, P_1_ID, true, etalonPrice);
xmlValidator.validateBillingResultXML();
}
/**
* Creates a time period for the week in which the specified date/time
* falls, calculated relative to the specified time zone.
*
* @param time the date/time (<code>null</code> not permitted).
* @param zone the time zone (<code>null</code> not permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @since 1.0.7
*/
public Week(Date time, TimeZone zone, Locale locale) {
ParamChecks.nullNotPermitted(time, "time");
ParamChecks.nullNotPermitted(zone, "zone");
ParamChecks.nullNotPermitted(locale, "locale");
Calendar calendar = Calendar.getInstance(zone, locale);
calendar.setTime(time);
// sometimes the last few days of the year are considered to fall in
// the *first* week of the following year. Refer to the Javadocs for
// GregorianCalendar.
int tempWeek = calendar.get(Calendar.WEEK_OF_YEAR);
if (tempWeek == 1
&& calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
this.week = 1;
this.year = (short) (calendar.get(Calendar.YEAR) + 1);
}
else {
this.week = (byte) Math.min(tempWeek, LAST_WEEK_IN_YEAR);
int yyyy = calendar.get(Calendar.YEAR);
// alternatively, sometimes the first few days of the year are
// considered to fall in the *last* week of the previous year...
if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
&& this.week >= 52) {
yyyy--;
}
this.year = (short) yyyy;
}
peg(calendar);
}
/**
* Creates a time period for the week in which the specified date/time
* falls, calculated relative to the specified time zone.
*
* @param time the date/time (<code>null</code> not permitted).
* @param zone the time zone (<code>null</code> not permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @since 1.0.7
*/
public Week(Date time, TimeZone zone, Locale locale) {
if (time == null) {
throw new IllegalArgumentException("Null 'time' argument.");
}
if (zone == null) {
throw new IllegalArgumentException("Null 'zone' argument.");
}
if (locale == null) {
throw new IllegalArgumentException("Null 'locale' argument.");
}
Calendar calendar = Calendar.getInstance(zone, locale);
calendar.setTime(time);
// sometimes the last few days of the year are considered to fall in
// the *first* week of the following year. Refer to the Javadocs for
// GregorianCalendar.
int tempWeek = calendar.get(Calendar.WEEK_OF_YEAR);
if (tempWeek == 1
&& calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
this.week = 1;
this.year = (short) (calendar.get(Calendar.YEAR) + 1);
}
else {
this.week = (byte) Math.min(tempWeek, LAST_WEEK_IN_YEAR);
int yyyy = calendar.get(Calendar.YEAR);
// alternatively, sometimes the first few days of the year are
// considered to fall in the *last* week of the previous year...
if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
&& this.week >= 52) {
yyyy--;
}
this.year = (short) yyyy;
}
peg(calendar);
}
/**
* Before the fix, JDK8 prints: {@code
* <record>
* <date>3913-11-18T17:35:40</date>
* <millis>1384792540403</millis>
* <sequence>0</sequence>
* <level>INFO</level>
* <thread>1</thread>
* <message>test</message>
* </record>
* }
* After the fix, it should print: {@code
* <record>
* <date>2013-11-18T17:35:40</date>
* <millis>1384792696519</millis>
* <sequence>0</sequence>
* <level>INFO</level>
* <thread>1</thread>
* <message>test</message>
* </record>
* }
* @param args the command line arguments
*/
public static void main(String[] args) {
Locale locale = Locale.getDefault();
try {
Locale.setDefault(Locale.ENGLISH);
final GregorianCalendar cal1 = new GregorianCalendar();
final int year1 = cal1.get(Calendar.YEAR);
LogRecord record = new LogRecord(Level.INFO, "test");
XMLFormatter formatter = new XMLFormatter();
final String formatted = formatter.format(record);
System.out.println(formatted);
final GregorianCalendar cal2 = new GregorianCalendar();
final int year2 = cal2.get(Calendar.YEAR);
if (year2 < 1900) {
throw new Error("Invalid system year: " + year2);
}
StringBuilder buf2 = new StringBuilder()
.append("<date>").append(year2).append("-");
if (!formatted.contains(buf2.toString())) {
StringBuilder buf1 = new StringBuilder()
.append("<date>").append(year1).append("-");
if (formatted.contains(buf1)
&& year2 == year1 + 1
&& cal2.get(Calendar.MONTH) == Calendar.JANUARY
&& cal2.get(Calendar.DAY_OF_MONTH) == 1) {
// Oh! The year just switched in the midst of the test...
System.out.println("Happy new year!");
} else {
throw new Error("Expected year " + year2
+ " not found in log:\n" + formatted);
}
}
} finally {
Locale.setDefault(locale);
}
}
/**
* Returns the time elapsed so far this year in milliseconds.
*
* @return Time elapsed this year in milliseconds.
*/
public long getElapsedYear() {
// Today + rest of this month + previous months until January
long elapsed = getElapsedMonth();
int month = calendar.get(Calendar.MONTH) - 1;
int year = calendar.get(Calendar.YEAR);
while (month > Calendar.JANUARY) {
elapsed += getDaysInMonth(year, month) * MS_PER_DAY;
month--;
}
return elapsed;
}
private static int getMonth(String monthString) {
int hash = Character.toLowerCase(monthString.charAt(0)) +
Character.toLowerCase(monthString.charAt(1)) +
Character.toLowerCase(monthString.charAt(2)) - 3 * 'a';
switch (hash) {
case 22:
return Calendar.JANUARY;
case 10:
return Calendar.FEBRUARY;
case 29:
return Calendar.MARCH;
case 32:
return Calendar.APRIL;
case 36:
return Calendar.MAY;
case 42:
return Calendar.JUNE;
case 40:
return Calendar.JULY;
case 26:
return Calendar.AUGUST;
case 37:
return Calendar.SEPTEMBER;
case 35:
return Calendar.OCTOBER;
case 48:
return Calendar.NOVEMBER;
case 9:
return Calendar.DECEMBER;
default:
throw new IllegalArgumentException();
}
}
private static int getMonth(String monthString) {
int hash = Character.toLowerCase(monthString.charAt(0)) +
Character.toLowerCase(monthString.charAt(1)) +
Character.toLowerCase(monthString.charAt(2)) - 3 * 'a';
switch (hash) {
case 22:
return Calendar.JANUARY;
case 10:
return Calendar.FEBRUARY;
case 29:
return Calendar.MARCH;
case 32:
return Calendar.APRIL;
case 36:
return Calendar.MAY;
case 42:
return Calendar.JUNE;
case 40:
return Calendar.JULY;
case 26:
return Calendar.AUGUST;
case 37:
return Calendar.SEPTEMBER;
case 35:
return Calendar.OCTOBER;
case 48:
return Calendar.NOVEMBER;
case 9:
return Calendar.DECEMBER;
default:
throw new IllegalArgumentException();
}
}
public static long parse(String timeString) throws IllegalArgumentException {
int date = 1;
int month = Calendar.JANUARY;
int year = 1970;
TimeOfDay timeOfDay;
Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
if (rfcMatcher.find()) {
date = getDate(rfcMatcher.group(1));
month = getMonth(rfcMatcher.group(2));
year = getYear(rfcMatcher.group(3));
timeOfDay = getTime(rfcMatcher.group(4));
} else {
Matcher ansicMatcher = HTTP_DATE_ANSIC_PATTERN.matcher(timeString);
if (ansicMatcher.find()) {
month = getMonth(ansicMatcher.group(1));
date = getDate(ansicMatcher.group(2));
timeOfDay = getTime(ansicMatcher.group(3));
year = getYear(ansicMatcher.group(4));
} else {
throw new IllegalArgumentException();
}
}
// FIXME: Y2038 BUG!
if (year >= 2038) {
year = 2038;
month = Calendar.JANUARY;
date = 1;
}
Time time = new Time(Time.TIMEZONE_UTC);
time.set(timeOfDay.second, timeOfDay.minute, timeOfDay.hour, date,
month, year);
return time.toMillis(false /* use isDst */);
}
/**
* Before the fix, JDK8 prints: {@code
* <record>
* <date>3913-11-18T17:35:40</date>
* <millis>1384792540403</millis>
* <sequence>0</sequence>
* <level>INFO</level>
* <thread>1</thread>
* <message>test</message>
* </record>
* }
* After the fix, it should print: {@code
* <record>
* <date>2013-11-18T17:35:40</date>
* <millis>1384792696519</millis>
* <sequence>0</sequence>
* <level>INFO</level>
* <thread>1</thread>
* <message>test</message>
* </record>
* }
* @param args the command line arguments
*/
public static void main(String[] args) {
Locale locale = Locale.getDefault();
try {
Locale.setDefault(Locale.ENGLISH);
final GregorianCalendar cal1 = new GregorianCalendar();
final int year1 = cal1.get(Calendar.YEAR);
LogRecord record = new LogRecord(Level.INFO, "test");
XMLFormatter formatter = new XMLFormatter();
final String formatted = formatter.format(record);
System.out.println(formatted);
final GregorianCalendar cal2 = new GregorianCalendar();
final int year2 = cal2.get(Calendar.YEAR);
if (year2 < 1900) {
throw new Error("Invalid system year: " + year2);
}
StringBuilder buf2 = new StringBuilder()
.append("<date>").append(year2).append("-");
if (!formatted.contains(buf2.toString())) {
StringBuilder buf1 = new StringBuilder()
.append("<date>").append(year1).append("-");
if (formatted.contains(buf1)
&& year2 == year1 + 1
&& cal2.get(Calendar.MONTH) == Calendar.JANUARY
&& cal2.get(Calendar.DAY_OF_MONTH) == 1) {
// Oh! The year just switched in the midst of the test...
System.out.println("Happy new year!");
} else {
throw new Error("Expected year " + year2
+ " not found in log:\n" + formatted);
}
}
} finally {
Locale.setDefault(locale);
}
}
/**
* Minimum and Maximum enable month in picker (0-11 for compatibility with Calender.MONTH or
* Calendar.JANUARY, Calendar.FEBRUARY etc).
*
* @param minMonth minimum enabled month.
* @param maxMonth maximum enabled month.
* @return Builder
*/
public Builder setMonthRange(@IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER)
int minMonth,
@IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER)
int maxMonth) {
if (minMonth >= Calendar.JANUARY && minMonth <= Calendar.DECEMBER &&
maxMonth >= Calendar.JANUARY && maxMonth <= Calendar.DECEMBER) {
this._minMonth = minMonth;
this._maxMonth = maxMonth;
return this;
} else {
throw new IllegalArgumentException("Month range should be between 0 " +
"(Calender.JANUARY) to 11 (Calendar.DECEMBER)");
}
}
private static boolean isValidMonth(int month) {
return month >= Calendar.JANUARY && month <= Calendar.DECEMBER;
}
public void initAlarmForTenant(SbiTenant tenant) {
try {
logger.debug("IN");
boolean alreadyInDB = false;
ISchedulerDAO schedulerDAO = DAOFactory.getSchedulerDAO();
schedulerDAO.setTenant(tenant.getName());
alreadyInDB = schedulerDAO.jobExists("AlarmInspectorJob", "AlarmInspectorJob");
if (!alreadyInDB) {
// CREATE JOB DETAIL
Job jobDetail = new Job();
jobDetail.setName("AlarmInspectorJob");
jobDetail.setGroupName("AlarmInspectorJob");
jobDetail.setDescription("AlarmInspectorJob");
jobDetail.setDurable(true);
jobDetail.setVolatile(false);
jobDetail.setRequestsRecovery(true);
schedulerDAO.insertJob(jobDetail);
Calendar startDate = new java.util.GregorianCalendar(2012, Calendar.JANUARY, 01);
startDate.set(Calendar.AM_PM, Calendar.AM);
startDate.set(Calendar.HOUR, 00);
startDate.set(Calendar.MINUTE, 00);
startDate.set(Calendar.SECOND, 0);
startDate.set(Calendar.MILLISECOND, 0);
String nameTrig = "schedule_uuid_" + UUIDGenerator.getInstance().generateTimeBasedUUID().toString();
CronExpression cronExpression = new CronExpression("minute{numRepetition=5}");
Trigger simpleTrigger = new Trigger();
simpleTrigger.setName(nameTrig);
simpleTrigger.setStartTime(startDate.getTime());
simpleTrigger.setJob(jobDetail);
simpleTrigger.setCronExpression(cronExpression);
simpleTrigger.setRunImmediately(false);
schedulerDAO.insertTrigger(simpleTrigger);
logger.debug("Added job with name AlarmInspectorJob");
}
logger.debug("OUT");
} catch (Exception e) {
logger.error("Error while initializing scheduler ", e);
}
}
void testInsert()
{
//test sync
IGISApplication application = (IGISApplication) getApplication();
MapBase map = application.getMap();
NGWVectorLayer ngwVectorLayer = null;
for (int i = 0; i < map.getLayerCount(); i++) {
ILayer layer = map.getLayer(i);
if (layer instanceof NGWVectorLayer) {
ngwVectorLayer = (NGWVectorLayer) layer;
}
}
if (null != ngwVectorLayer) {
Uri uri = Uri.parse(
"content://" + AppSettingsConstants.AUTHORITY + "/" +
ngwVectorLayer.getPath().getName());
ContentValues values = new ContentValues();
//values.put(VectorLayer.FIELD_ID, 26);
values.put("width", 1);
values.put("azimuth", 2.0);
values.put("status", "grot");
values.put("temperatur", -13);
values.put("name", "get");
Calendar calendar = new GregorianCalendar(2015, Calendar.JANUARY, 23);
values.put("datetime", calendar.getTimeInMillis());
try {
GeoPoint pt = new GeoPoint(37, 55);
pt.setCRS(CRS_WGS84);
pt.project(CRS_WEB_MERCATOR);
GeoMultiPoint mpt = new GeoMultiPoint();
mpt.add(pt);
values.put(Constants.FIELD_GEOM, mpt.toBlob());
} catch (IOException e) {
e.printStackTrace();
}
Uri result = getContentResolver().insert(uri, values);
if(Constants.DEBUG_MODE){
if (result == null) {
Log.d(TAG, "insert failed");
} else {
Log.d(TAG, result.toString());
}
}
}
}
static NMonthlyPeriodGenerator sixMonthly(Calendar calendar) {
return new NMonthlyPeriodGenerator(calendar, PeriodType.SixMonthly, 6,
"S", Calendar.JANUARY);
}