Java Code Examples for java.util.Calendar.clear()

The following are Jave code examples for showing how to use clear() of the java.util.Calendar class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ConnectU   File: UpdaterHelper.java   View Source Code Vote up 7 votes
public static boolean needsSilenceUpdate(long value) { //Silence Update

        /*If one os those get executed no one else will be
        until it reach the next week or month change usually.
        */

        if (value < 1) //Is First Launch ---> Like Really???, Will you launch it some day???
            return true;

        if (!isTheSameYear(value)) //New Year Update
            return true;

        if (!isTheSameMonth(value)) //New Month Update
            return true;

        //Weekly update
        Calendar current = Calendar.getInstance();
        Calendar old = Calendar.getInstance();
        old.clear();
        old.setTimeInMillis(value);
        return current.get(Calendar. WEEK_OF_YEAR) != old.get(Calendar. WEEK_OF_YEAR);

    }
 
Example 2
Project: rotabuilder   File: ShiftDate.java   View Source Code Vote up 7 votes
public String determineNextDateString() {
    TimeZone LOCAL_TIMEZONE = TimeZone.getTimeZone("GMT");
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(LOCAL_TIMEZONE);
    calendar.clear();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setCalendar(calendar);
    Date date;
    try {
        date = dateFormat.parse(dateString);
    } catch (ParseException e) {
        throw new IllegalStateException("Could not parse shiftDate (" + this
                + ")'s dateString (" + dateString + ").");
    }
    calendar.setTime(date);
    calendar.add(Calendar.DAY_OF_YEAR, 1);
    return dateFormat.format(calendar.getTime());
}
 
Example 3
Project: parabuild-ci   File: Week.java   View Source Code Vote up 6 votes
/**
 * Returns the last millisecond of the week, evaluated using the supplied
 * calendar (which determines the time zone).
 *
 * @param calendar  the calendar (<code>null</code> not permitted).
 *
 * @return The last millisecond of the week.
 *
 * @throws NullPointerException if <code>calendar</code> is 
 *     <code>null</code>.
 */
public long getLastMillisecond(Calendar calendar) {
    Calendar c = (Calendar) calendar.clone();
    c.clear();
    c.set(Calendar.YEAR, this.year);
    c.set(Calendar.WEEK_OF_YEAR, this.week + 1);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    c.set(Calendar.HOUR, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    //return c.getTimeInMillis();  // this won't work for JDK 1.3
    return c.getTime().getTime() - 1;
}
 
Example 4
Project: OpenVertretung   File: TimeUtil.java   View Source Code Vote up 6 votes
final static Time fastTimeCreate(Calendar cal, int hour, int minute, int second, ExceptionInterceptor exceptionInterceptor) throws SQLException {
    if (hour < 0 || hour > 24) {
        throw SQLError.createSQLException(
                "Illegal hour value '" + hour + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
    }

    if (minute < 0 || minute > 59) {
        throw SQLError.createSQLException(
                "Illegal minute value '" + minute + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
    }

    if (second < 0 || second > 59) {
        throw SQLError.createSQLException(
                "Illegal minute value '" + second + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
    }

    synchronized (cal) {
        java.util.Date origCalDate = cal.getTime();
        try {
            cal.clear();

            // Set 'date' to epoch of Jan 1, 1970
            cal.set(1970, 0, 1, hour, minute, second);

            long timeAsMillis = cal.getTimeInMillis();

            return new Time(timeAsMillis);
        } finally {
            cal.setTime(origCalDate);
        }
    }
}
 
Example 5
Project: ibm-cos-sdk-java   File: SimpleTypeIonUnmarshallersTest.java   View Source Code Vote up 6 votes
@Test
public void unmarshalDate() throws Exception {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.clear();
    calendar.set(2000, 0, 1); // Month is zero-based
    assertEquals(calendar.getTime(), DateIonUnmarshaller.getInstance().unmarshall(context("2000-01-01T")));
}
 
Example 6
Project: unitimes   File: TimePatternModel.java   View Source Code Vote up 6 votes
public long getTime(int time) {
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(Calendar.HOUR_OF_DAY, iMinutes[time]/60);
    cal.set(Calendar.MINUTE, iMinutes[time]%60);

    return cal.getTimeInMillis();
}
 
Example 7
Project: workdays   File: FileHolidayProvider.java   View Source Code Vote up 6 votes
/**
 * Checks if the given date is a holiday.
 * @param cal date to check
 * @return true, if date is a holiday, otherwise false
 */
@Override
public boolean isHoliday(Calendar cal) {
    Objects.requireNonNull(cal, "parameter cal must not be null!");

    // clear time in given date (cal)
    cal.set(java.util.Calendar.HOUR_OF_DAY, 0);
    cal.clear(java.util.Calendar.MINUTE);
    cal.clear(java.util.Calendar.SECOND);

    // create filter for search in calendar
    Period period = new Period(new DateTime(cal.getTime()), new Dur(1, 0, 0, 0));
    Filter filter = new Filter(new PeriodRule(period));

    // get all events for the given date
    Collection<VEvent> filteredEvents = filter.filter(calendar.getComponents(Component.VEVENT));

    // here is a little workaround: if we have an event for the given date in the holiday calendar
    // then the given date must be a holiday. however, ical4j returns an event even for the day
    // after the holiday. so we check if the endDate of the event is our date. in that case, we ignore
    // the event und return false.
    if(filteredEvents.size() == 1) {
        VEvent event = filteredEvents.iterator().next();

        GregorianCalendar endDateCal = new GregorianCalendar();
        endDateCal.setTime(event.getEndDate().getDate());

        if(endDateCal.get(Calendar.MONTH) == cal.get(Calendar.MONTH)
                && endDateCal.get(Calendar.DATE) == cal.get(Calendar.DATE)) {
            return false;
        }

        return true;
    }

    return filteredEvents.size() > 0;
}
 
Example 8
Project: android-AutofillFramework   File: CreditCardExpirationDateCompoundView.java   View Source Code Vote up 6 votes
@Override
public AutofillValue getAutofillValue() {
    Calendar calendar = Calendar.getInstance();
    // Set hours, minutes, seconds, and millis to 0 to ensure getAutofillValue() == the value
    // set by autofill(). Without this line, the view will not turn yellow when updated.
    calendar.clear();
    int year = Integer.parseInt(mCcExpYearSpinner.getSelectedItem().toString());
    int month = mCcExpMonthSpinner.getSelectedItemPosition();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    long unixTime = calendar.getTimeInMillis();
    return AutofillValue.forDate(unixTime);
}
 
Example 9
Project: sstore-soft   File: ReturnFlight.java   View Source Code Vote up 6 votes
/**
 * 
 * @param flight_date
 * @param return_days
 * @return
 */
protected static final TimestampType calculateReturnDate(TimestampType flight_date, int return_days) {
    assert(return_days >= 0);
    // Round this to the start of the day
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(flight_date.getTime() + (return_days * SEATSConstants.MICROSECONDS_PER_DAY));
    
    int year = cal.get(Calendar.YEAR);
    int month= cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH);
    
    cal.clear();
    cal.set(year, month, day);
    return (new TimestampType(cal.getTime()));
}
 
Example 10
Project: mumu-core   File: DateUtils.java   View Source Code Vote up 6 votes
/**
 * 根据单位字段比较两个时间
 * 
 * @param date
 *            时间1
 * @param otherDate
 *            时间2
 * @param withUnit
 *            单位字段,从Calendar field取值
 * @return 等于返回0值, 大于返回大于0的值 小于返回小于0的值
 */
public static int compareTime(Date date, Date otherDate, int withUnit) {
	Calendar dateCal = Calendar.getInstance();
	dateCal.setTime(date);
	Calendar otherDateCal = Calendar.getInstance();
	otherDateCal.setTime(otherDate);

	dateCal.clear(Calendar.YEAR);
	dateCal.clear(Calendar.MONTH);
	dateCal.set(Calendar.DATE, 1);
	otherDateCal.clear(Calendar.YEAR);
	otherDateCal.clear(Calendar.MONTH);
	otherDateCal.set(Calendar.DATE, 1);
	switch (withUnit) {
	case Calendar.HOUR:
		dateCal.clear(Calendar.MINUTE);
		otherDateCal.clear(Calendar.MINUTE);
	case Calendar.MINUTE:
		dateCal.clear(Calendar.SECOND);
		otherDateCal.clear(Calendar.SECOND);
	case Calendar.SECOND:
		dateCal.clear(Calendar.MILLISECOND);
		otherDateCal.clear(Calendar.MILLISECOND);
	case Calendar.MILLISECOND:
		break;
	default:
		throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
	}
	return dateCal.compareTo(otherDateCal);
}
 
Example 11
Project: ProyectoPacientes   File: TimeUtil.java   View Source Code Vote up 6 votes
final static Time fastTimeCreate(Calendar cal, int hour, int minute, int second, ExceptionInterceptor exceptionInterceptor) throws SQLException {
    if (hour < 0 || hour > 24) {
        throw SQLError.createSQLException(
                "Illegal hour value '" + hour + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
    }

    if (minute < 0 || minute > 59) {
        throw SQLError.createSQLException(
                "Illegal minute value '" + minute + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
    }

    if (second < 0 || second > 59) {
        throw SQLError.createSQLException(
                "Illegal minute value '" + second + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
    }

    synchronized (cal) {
        java.util.Date origCalDate = cal.getTime();
        try {
            cal.clear();

            // Set 'date' to epoch of Jan 1, 1970
            cal.set(1970, 0, 1, hour, minute, second);

            long timeAsMillis = cal.getTimeInMillis();

            return new Time(timeAsMillis);
        } finally {
            cal.setTime(origCalDate);
        }
    }
}
 
Example 12
Project: OpenJSharp   File: KerberosTime.java   View Source Code Vote up 6 votes
/**
 * Returns a string representation of KerberosTime object.
 * @return a string representation of this object.
 */
public String toGeneralizedTimeString() {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.clear();

    calendar.setTimeInMillis(kerberosTime);
    return String.format("%04d%02d%02d%02d%02d%02dZ",
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH) + 1,
            calendar.get(Calendar.DAY_OF_MONTH),
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            calendar.get(Calendar.SECOND));
}
 
Example 13
Project: marathonv5   File: DataAppLoader.java   View Source Code Vote up 6 votes
/**
 * @param args the command line arguments
 */
@PersistenceUnit
public static void main(String[] args) {
    System.out.println("Creating entity information...");
    EntityManager entityManager = Persistence.createEntityManagerFactory("DataAppLibraryPULocal").createEntityManager();
    EntityTransaction et = entityManager.getTransaction();
    et.begin();
    loadDiscountRate(entityManager);
    loadRegion(entityManager);
    loadRole(entityManager);
    loadTransmission(entityManager);
    loadProductType(entityManager);
    loadEngine(entityManager);
    loadProduct(entityManager);
    et.commit();
    
    
    EntityManager specialEntityManager = new InitialLoadEntityManagerProxy(entityManager);
    SalesSimulator simulator = new SalesSimulator(specialEntityManager);
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    cal.clear();
    cal.set(year-1, 0, 1, 0, 0, 0); // go back to begining of year, 3 years ago
    System.out.println("Creating historical data...");
    System.out.println("        This may take 5 to 15min depending on machine speed.");
    simulator.run(cal.getTime(), new Date());
    
    entityManager.close();
}
 
Example 14
Project: CalendarFX   File: TimeUtils.java   View Source Code Vote up 6 votes
/**
 * Get a "time_t" in millis given a number of seconds since
 * Dershowitz/Reingold epoch relative to a given timezone.
 * @param epochSecs Number of seconds since Dershowitz/Reingold
 * epoch, relatve to zone.
 * @param zone Timezone against which epochSecs applies
 * @return Number of milliseconds since 00:00:00 Jan 1, 1970 GMT
 */
private static long timetMillisFromEpochSecs(long epochSecs,
                                             TimeZone zone) {
    DateTimeValue date = timeFromSecsSinceEpoch(epochSecs);
    Calendar cal = new GregorianCalendar(zone);
    cal.clear(); // clear millis
    cal.setTimeZone(zone);
    cal.set(date.year(), date.month() - 1, date.day(),
            date.hour(), date.minute(), date.second());
    return cal.getTimeInMillis();
}
 
Example 15
Project: the-vigilantes   File: TimeUtil.java   View Source Code Vote up 6 votes
final static Timestamp fastTimestampCreate(TimeZone tz, int year, int month, int day, int hour, int minute, int seconds, int secondsPart) {
    Calendar cal = (tz == null) ? new GregorianCalendar() : new GregorianCalendar(tz);
    cal.clear();

    // why-oh-why is this different than java.util.date, in the year part, but it still keeps the silly '0' for the start month????
    cal.set(year, month - 1, day, hour, minute, seconds);

    long tsAsMillis = cal.getTimeInMillis();

    Timestamp ts = new Timestamp(tsAsMillis);
    ts.setNanos(secondsPart);

    return ts;
}
 
Example 16
Project: flume-release-1.7.0   File: TestHiveSink.java   View Source Code Vote up 5 votes
@Test
public void testSingleWriterUseHeaders()
        throws Exception {
  String[] colNames = {COL1, COL2};
  String PART1_NAME = "country";
  String PART2_NAME = "hour";
  String[] partNames = {PART1_NAME, PART2_NAME};
  List<String> partitionVals = null;
  String PART1_VALUE = "%{" + PART1_NAME + "}";
  String PART2_VALUE = "%y-%m-%d-%k";
  partitionVals = new ArrayList<String>(2);
  partitionVals.add(PART1_VALUE);
  partitionVals.add(PART2_VALUE);

  String tblName = "hourlydata";
  TestUtil.dropDB(conf, dbName2);
  String dbLocation = dbFolder.newFolder(dbName2).getCanonicalPath() + ".db";
  dbLocation = dbLocation.replaceAll("\\\\","/"); // for windows paths
  TestUtil.createDbAndTable(driver, dbName2, tblName, partitionVals, colNames,
          colTypes, partNames, dbLocation);

  int totalRecords = 4;
  int batchSize = 2;
  int batchCount = totalRecords / batchSize;

  Context context = new Context();
  context.put("hive.metastore",metaStoreURI);
  context.put("hive.database",dbName2);
  context.put("hive.table",tblName);
  context.put("hive.partition", PART1_VALUE + "," + PART2_VALUE);
  context.put("autoCreatePartitions","true");
  context.put("useLocalTimeStamp", "false");
  context.put("batchSize","" + batchSize);
  context.put("serializer", HiveDelimitedTextSerializer.ALIAS);
  context.put("serializer.fieldnames", COL1 + ",," + COL2 + ",");
  context.put("heartBeatInterval", "0");

  Channel channel = startSink(sink, context);

  Calendar eventDate = Calendar.getInstance();
  List<String> bodies = Lists.newArrayList();

  // push events in two batches - two per batch. each batch is diff hour
  Transaction txn = channel.getTransaction();
  txn.begin();
  for (int j = 1; j <= totalRecords; j++) {
    Event event = new SimpleEvent();
    String body = j + ",blah,This is a log message,other stuff";
    event.setBody(body.getBytes());
    eventDate.clear();
    eventDate.set(2014, 03, 03, j % batchCount, 1); // yy mm dd hh mm
    event.getHeaders().put( "timestamp",
            String.valueOf(eventDate.getTimeInMillis()) );
    event.getHeaders().put( PART1_NAME, "Asia" );
    bodies.add(body);
    channel.put(event);
  }
  // execute sink to process the events
  txn.commit();
  txn.close();

  checkRecordCountInTable(0, dbName2, tblName);
  for (int i = 0; i < batchCount ; i++) {
    sink.process();
  }
  checkRecordCountInTable(totalRecords, dbName2, tblName);
  sink.stop();

  // verify counters
  SinkCounter counter = sink.getCounter();
  Assert.assertEquals(2, counter.getConnectionCreatedCount());
  Assert.assertEquals(2, counter.getConnectionClosedCount());
  Assert.assertEquals(2, counter.getBatchCompleteCount());
  Assert.assertEquals(0, counter.getBatchEmptyCount());
  Assert.assertEquals(0, counter.getConnectionFailedCount() );
  Assert.assertEquals(4, counter.getEventDrainAttemptCount());
  Assert.assertEquals(4, counter.getEventDrainSuccessCount() );

}
 
Example 17
Project: flume-release-1.7.0   File: TestHDFSEventSink.java   View Source Code Vote up 5 votes
@Test
public void testTextAppend() throws InterruptedException, LifecycleException,
    EventDeliveryException, IOException {

  LOG.debug("Starting...");
  final long rollCount = 3;
  final long batchSize = 2;
  final String fileName = "FlumeData";
  String newPath = testPath + "/singleTextBucket";
  int totalEvents = 0;
  int i = 1, j = 1;

  // clear the test directory
  Configuration conf = new Configuration();
  FileSystem fs = FileSystem.get(conf);
  Path dirPath = new Path(newPath);
  fs.delete(dirPath, true);
  fs.mkdirs(dirPath);

  Context context = new Context();

  // context.put("hdfs.path", testPath + "/%Y-%m-%d/%H");
  context.put("hdfs.path", newPath);
  context.put("hdfs.filePrefix", fileName);
  context.put("hdfs.rollCount", String.valueOf(rollCount));
  context.put("hdfs.batchSize", String.valueOf(batchSize));
  context.put("hdfs.writeFormat", "Text");
  context.put("hdfs.fileType", "DataStream");

  Configurables.configure(sink, context);

  Channel channel = new MemoryChannel();
  Configurables.configure(channel, context);

  sink.setChannel(channel);
  sink.start();

  Calendar eventDate = Calendar.getInstance();
  List<String> bodies = Lists.newArrayList();

  // push the event batches into channel
  for (i = 1; i < 4; i++) {
    Transaction txn = channel.getTransaction();
    txn.begin();
    for (j = 1; j <= batchSize; j++) {
      Event event = new SimpleEvent();
      eventDate.clear();
      eventDate.set(2011, i, i, i, 0); // yy mm dd
      event.getHeaders().put("timestamp",
          String.valueOf(eventDate.getTimeInMillis()));
      event.getHeaders().put("hostname", "Host" + i);
      String body = "Test." + i + "." + j;
      event.setBody(body.getBytes());
      bodies.add(body);
      channel.put(event);
      totalEvents++;
    }
    txn.commit();
    txn.close();

    // execute sink to process the events
    sink.process();
  }

  sink.stop();

  // loop through all the files generated and check their contains
  FileStatus[] dirStat = fs.listStatus(dirPath);
  Path[] fList = FileUtil.stat2Paths(dirStat);

  // check that the roll happened correctly for the given data
  long expectedFiles = totalEvents / rollCount;
  if (totalEvents % rollCount > 0) expectedFiles++;
  Assert.assertEquals("num files wrong, found: " +
      Lists.newArrayList(fList), expectedFiles, fList.length);
  verifyOutputTextFiles(fs, conf, dirPath.toUri().getPath(), fileName, bodies);
}
 
Example 18
Project: airgram   File: Util.java   View Source Code Vote up 5 votes
/**
 * Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since
 * the epoch.
 *
 * @param value The attribute value to parse.
 * @return The parsed timestamp in milliseconds since the epoch.
 */
public static long parseXsDateTime(String value) throws ParseException {
  Matcher matcher = XS_DATE_TIME_PATTERN.matcher(value);
  if (!matcher.matches()) {
    throw new ParseException("Invalid date/time format: " + value, 0);
  }

  int timezoneShift;
  if (matcher.group(9) == null) {
    // No time zone specified.
    timezoneShift = 0;
  } else if (matcher.group(9).equalsIgnoreCase("Z")) {
    timezoneShift = 0;
  } else {
    timezoneShift = ((Integer.parseInt(matcher.group(12)) * 60
        + Integer.parseInt(matcher.group(13))));
    if (matcher.group(11).equals("-")) {
      timezoneShift *= -1;
    }
  }

  Calendar dateTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

  dateTime.clear();
  // Note: The month value is 0-based, hence the -1 on group(2)
  dateTime.set(Integer.parseInt(matcher.group(1)),
               Integer.parseInt(matcher.group(2)) - 1,
               Integer.parseInt(matcher.group(3)),
               Integer.parseInt(matcher.group(4)),
               Integer.parseInt(matcher.group(5)),
               Integer.parseInt(matcher.group(6)));
  if (!TextUtils.isEmpty(matcher.group(8))) {
    final BigDecimal bd = new BigDecimal("0." + matcher.group(8));
    // we care only for milliseconds, so movePointRight(3)
    dateTime.set(Calendar.MILLISECOND, bd.movePointRight(3).intValue());
  }

  long time = dateTime.getTimeInMillis();
  if (timezoneShift != 0) {
    time -= timezoneShift * 60000;
  }

  return time;
}
 
Example 19
Project: GrowingProject   File: DateUtils.java   View Source Code Vote up 4 votes
/**
 * 返回指定为年度为year月度为month的月份内,第weekOfMonth个星期的第dayOfWeek天。<br>
 * 00 00 00 01 02 03 04 <br>
 * 05 06 07 08 09 10 11<br>
 * 12 13 14 15 16 17 18<br>
 * 19 20 21 22 23 24 25<br>
 * 26 27 28 29 30 31 <br>
 * 2006年的第一个周的1到7天为:05 06 07 01 02 03 04 <br>
 * 2006年的第二个周的1到7天为:12 13 14 08 09 10 11 <br>
 * 2006年的第三个周的1到7天为:19 20 21 15 16 17 18 <br>
 * 2006年的第四个周的1到7天为:26 27 28 22 23 24 25 <br>
 * 2006年的第五个周的1到7天为:02 03 04 29 30 31 01 。本月没有就自动转到下个月了。
 *
 * @param year        形式为yyyy <br>
 * @param month       形式为MM,参数值在[1-12]。<br>
 * @param weekOfMonth 在[1-6],因为一个月最多有6个周。<br>
 * @param dayOfWeek   数字在1到7之间,包括1和7。1表示星期天,7表示星期六<br>
 *                    -6为星期日-1为星期五,0为星期六 <br>
 * @return <type>int</type>
 */
public static int getDayofWeekInMonth(String year, String month, String weekOfMonth, String dayOfWeek) {
    Calendar cal = new GregorianCalendar();
    // 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。
    int y = new Integer(year).intValue();
    int m = new Integer(month).intValue();
    cal.clear();// 不保留以前的设置
    cal.set(y, m - 1, 1);// 将日期设置为本月的第一天。
    cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, new Integer(weekOfMonth).intValue());
    cal.set(Calendar.DAY_OF_WEEK, new Integer(dayOfWeek).intValue());
    // System.out.print(cal.get(Calendar.MONTH)+" ");
    // System.out.print("当"+cal.get(Calendar.WEEK_OF_MONTH)+"\t");
    // WEEK_OF_MONTH表示当天在本月的第几个周。不管1号是星期几,都表示在本月的第一个周
    return cal.get(Calendar.DAY_OF_MONTH);
}
 
Example 20
Project: opencps-v2   File: DateTimeUtils.java   View Source Code Vote up 4 votes
public static String getMailSendDate() {
	Calendar cal = Calendar.getInstance();
	cal.clear();
	cal.setTime(new Date());
	
	return "Ng\u00E0y "+ cal.get(Calendar.DAY_OF_MONTH) + " th\u00E1ng " + ( cal.get(Calendar.MONTH) + 1 ) + " n\u0103m " + cal.get(Calendar.YEAR) ;
	
	
}