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

The following examples show how to use java.util.Calendar#clear() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BirtDateTimeTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Test
   public void testNow( )
{
	Calendar c = Calendar.getInstance( );
	c.clear( );
	Date d = (Date) cx.evaluateString( scope,
			"BirtDateTime.now()",
			"inline",
			1,
			null );
	c.setTime( d );
	System.out.println( "year:"
			+ c.get( Calendar.YEAR ) + " month:" + c.get( Calendar.MONTH )
			+ " day:" + c.get( Calendar.DATE ) + " hour:"
			+ c.get( Calendar.HOUR ) + " minute:" + c.get( Calendar.MINUTE )
			+ "second:" + c.get( Calendar.SECOND ) );
}
 
Example 2
Source File: FastDateParserTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testJpLocales() {

    final Calendar cal= Calendar.getInstance(GMT);
    cal.clear();
    cal.set(2003, Calendar.FEBRUARY, 10);
    cal.set(Calendar.ERA, GregorianCalendar.BC);

    final Locale locale = LocaleUtils.toLocale("zh"); {
        // ja_JP_JP cannot handle dates before 1868 properly

        final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
        final DateParser fdf = getInstance(LONG_FORMAT, locale);

        try {
            checkParse(locale, cal, sdf, fdf);
        } catch(final ParseException ex) {
            Assert.fail("Locale "+locale+ " failed with "+LONG_FORMAT+"\n" + trimMessage(ex.toString()));
        }
    }
}
 
Example 3
Source File: KerberosTime.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static long toKerberosTime(String time) throws Asn1Exception {
    // ASN.1 GeneralizedTime format:

    // "19700101000000Z"
    //  |   | | | | | |
    //  0   4 6 8 | | |
    //           10 | |
    //             12 |
    //               14

    if (time.length() != 15)
        throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
    if (time.charAt(14) != 'Z')
        throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
    int year = Integer.parseInt(time.substring(0, 4));
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.clear(); // so that millisecond is zero
    calendar.set(year,
                 Integer.parseInt(time.substring(4, 6)) - 1,
                 Integer.parseInt(time.substring(6, 8)),
                 Integer.parseInt(time.substring(8, 10)),
                 Integer.parseInt(time.substring(10, 12)),
                 Integer.parseInt(time.substring(12, 14)));
    return calendar.getTimeInMillis();
}
 
Example 4
Source File: TimeUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static long getDayStartWithTimeZone(TimeZone timeZone, long ts){
    Calendar calendar = Calendar.getInstance(timeZone, Locale.ROOT);
    calendar.setTimeInMillis(ts);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int date = calendar.get(Calendar.DATE);
    calendar.clear();
    calendar.set(year, month, date);
    return calendar.getTimeInMillis();
}
 
Example 5
Source File: FastDateParserTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @throws ParseException
 */
@Test
public void testMilleniumBug() throws ParseException {
    final DateParser parser = getInstance(DMY_DOT);
    final Calendar cal = Calendar.getInstance();
    cal.clear();

    cal.set(1000,0,1);
    assertEquals(cal.getTime(), parser.parse("01.01.1000"));
}
 
Example 6
Source File: TimeUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static long getMonthStartWithTimeZone(TimeZone timeZone, long ts){
    Calendar calendar = Calendar.getInstance(timeZone, Locale.ROOT);
    calendar.setTimeInMillis(ts);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    calendar.clear();
    calendar.set(year, month, 1);
    return calendar.getTimeInMillis();
}
 
Example 7
Source File: DateUtil.java    From quickhybrid-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int getDaysOfYM(int year, int month) {
    Calendar time = Calendar.getInstance();
    time.clear();
    time.set(Calendar.YEAR, year);
    time.set(Calendar.MONTH, month - 1);
    int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);
    return day;
}
 
Example 8
Source File: DecorateCalendarPagerAdapter.java    From DecorateCalendarView with Apache License 2.0 5 votes vote down vote up
public Calendar getDisplayCalendar(int position) {
    int displayYear = mCurrentYear;
    if (0 <= position && position < 12) displayYear -= 2;
    else if (12 <= position && position < 12 * 2) displayYear -= 1;
    else if (12 * 2 <= position && position < 12 * 3) ; // current
    else if (12 * 3 <= position && position < 12 * 4) displayYear += 1;
    else if (12 * 4 <= position && position < 12 * 5) displayYear += 2;
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(displayYear, position % 12, 1);
    return calendar;
}
 
Example 9
Source File: SimpleTypeIonUnmarshallersTest.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: ArgumentResolverTest.java    From EasyNLU with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveShift() {
    Calendar c = Calendar.getInstance();

    c.clear();
    resolver.resolveShift("morning", c);
    assertEquals(9, c.get(Calendar.HOUR_OF_DAY));

    c.clear();
    resolver.resolveShift("noon", c);
    assertEquals(12, c.get(Calendar.HOUR_OF_DAY));

    c.clear();
    resolver.resolveShift("afternoon", c);
    assertEquals(14, c.get(Calendar.HOUR_OF_DAY));

    c.clear();
    resolver.resolveShift("evening", c);
    assertEquals(18, c.get(Calendar.HOUR_OF_DAY));

    c.clear();
    resolver.resolveShift("night", c);
    assertEquals(20, c.get(Calendar.HOUR_OF_DAY));
    assertEquals(0, c.get(Calendar.MINUTE));
    assertEquals(1970, c.get(Calendar.YEAR));
    assertEquals(Calendar.JANUARY, c.get(Calendar.MONTH));
    assertEquals(1, c.get(Calendar.DAY_OF_MONTH));
    assertEquals(0, c.get(Calendar.SECOND));
}
 
Example 11
Source File: Week.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 12
Source File: SQLTime.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
    * Convert a SQL TIME to a JDBC java.sql.Timestamp.
    * 
    * Behaviour is to set the date portion of the Timestamp
    * to the actual current date, which may not match the
    * SQL CURRENT DATE, which remains fixed for the lifetime
    * of a SQL statement. JDBC drivers (especially network client drivers)
    * could not be expected to fetch the CURRENT_DATE SQL value
    * on every query that involved a TIME value, so the current
    * date as seen by the JDBC client was picked as the logical behaviour.
    * See DERBY-1811.
 */
public Timestamp getTimestamp( Calendar cal)
{
	if (isNull())
		return null;
	else
	{
           if( cal == null)
           {
               // Calendar initialized to current date and time.
               cal = ClientSharedData.getDefaultCleanCalendar();
           }
           else
           {
               cal.clear();
           }
               // Set Calendar to current date and time
               // to pick up the current date. Time portion
               // will be overridden by this value's time.
               cal.setTimeInMillis(System.currentTimeMillis());
           
           SQLTime.setTimeInCalendar(cal, encodedTime);
         
           // Derby's resolution for the TIME type is only seconds.
		cal.set(Calendar.MILLISECOND, 0);
           
		return new Timestamp(cal.getTimeInMillis());
	}
}
 
Example 13
Source File: QueryDateTest.java    From LitePal with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryDate() {
	Calendar calendar = Calendar.getInstance();
	calendar.clear();
	calendar.set(1990, 9, 16, 0, 0, 0);
	Student student1 = new Student();
	student1.setName("Student 1");
	student1.setBirthday(calendar.getTime());
	student1.save();
	Student studentFromDB = LitePal.find(Student.class, student1.getId());
	assertEquals("Student 1", studentFromDB.getName());
	assertEquals(calendar.getTimeInMillis(), studentFromDB.getBirthday().getTime());
}
 
Example 14
Source File: TimeHandlingTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Create a Time object that has its date components
 * set to 1970/01/01 and its time to match the time
 * represented by t and cal. This matches Derby by
 * setting the milli-second component to zero.
 * <BR>
 * Note that the Time(long) constructor for java.sql.Time
 * does *not* set the date component to 1970/01/01.
 * This is a requirement for JDBC java.sql.Time values though
 */
private Time getTime19700101(String s, Calendar cal)
{
    cal.clear();
    // JDK 1.3 can't call this!
    // cal.setTimeInMillis(t);
    cal.setTime(Time.valueOf(s));
    cal.set(1970, Calendar.JANUARY, 1);
    cal.set(Calendar.MILLISECOND, 0);
    
    Time to =  new Time(cal.getTime().getTime());
    assertTime1970(to);
    return to;
}
 
Example 15
Source File: TestHDFSEventSink.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
@Test
public void testSlowAppendFailure() throws InterruptedException,
    LifecycleException, EventDeliveryException, IOException {

  LOG.debug("Starting...");
  final String fileName = "FlumeData";
  final long rollCount = 5;
  final long batchSize = 2;
  final int numBatches = 2;
  String newPath = testPath + "/singleBucket";
  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);

  // create HDFS sink with slow writer
  HDFSBadWriterFactory badWriterFactory = new HDFSBadWriterFactory();
  sink = new HDFSEventSink(badWriterFactory);

  Context context = new Context();
  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.fileType", HDFSBadWriterFactory.BadSequenceFileType);
  context.put("hdfs.callTimeout", Long.toString(1000));
  Configurables.configure(sink, context);

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

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

  Calendar eventDate = Calendar.getInstance();

  // push the event batches into channel
  for (i = 0; i < numBatches; 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);
      event.getHeaders().put("slow", "1500");
      event.setBody(("Test." + i + "." + j).getBytes());
      channel.put(event);
    }
    txn.commit();
    txn.close();

    // execute sink to process the events
    Status satus = sink.process();

    // verify that the append returned backoff due to timeotu
    Assert.assertEquals(satus, Status.BACKOFF);
  }

  sink.stop();
}
 
Example 16
Source File: DateTimeUtils.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static Calendar fromMilliseconds(final long ms) {
  final Calendar dateTime = Calendar.getInstance();
  dateTime.clear();
  dateTime.setTimeInMillis(ms);
  return dateTime;
}
 
Example 17
Source File: ExpandSelectITCase.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void readExpandSelect() {
  ODataEntityRequest<ClientEntity> request = getEdmEnabledClient().getRetrieveRequestFactory()
      .getEntityRequest(getClient().newURIBuilder(TecSvcConst.BASE_URI)
          .appendEntitySetSegment("ESTwoPrim").appendKeySegment(-365)
          .expand("NavPropertyETAllPrimMany($select=PropertyTimeOfDay,PropertySByte)")
          .select("PropertyString")
          .build());
  assertNotNull(request);
  setCookieHeader(request);

  final ODataRetrieveResponse<ClientEntity> response = request.execute();
  saveCookieHeader(response);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());

  final ClientEntity entity = response.getBody();
  assertNotNull(entity);

  assertNotNull(entity.getProperty("PropertyInt16"));

  final ClientProperty property = entity.getProperty("PropertyString");
  assertNotNull(property);
  assertNotNull(property.getPrimitiveValue());
  assertEquals("Test String2", property.getPrimitiveValue().toValue());

  if (isJson()) {
    assertNull(entity.getNavigationLink("NavPropertyETAllPrimOne"));
  } else {
    // in xml the links will be always present; but the content will not be if no $expand unlike
    // json;metadata=minimal; json=full is same as application/xml
    assertFalse(entity.getNavigationLink("NavPropertyETAllPrimOne") instanceof ClientInlineEntity);
  }

  final ClientLink link = entity.getNavigationLink("NavPropertyETAllPrimMany");
  assertNotNull(link);
  assertEquals(ClientLinkType.ENTITY_SET_NAVIGATION, link.getType());
  final ClientInlineEntitySet inlineEntitySet = link.asInlineEntitySet();
  assertNotNull(inlineEntitySet);
  final List<? extends ClientEntity> entities = inlineEntitySet.getEntitySet().getEntities();
  assertNotNull(entities);
  assertEquals(2, entities.size());
  final ClientEntity inlineEntity = entities.get(0);
  assertEquals(3, inlineEntity.getProperties().size());
  assertShortOrInt(-128, inlineEntity.getProperty("PropertySByte").getPrimitiveValue().toValue());
  Calendar time = Calendar.getInstance();
  time.clear();
  time.set(1970, Calendar.JANUARY, 1, 23, 49, 14);
  assertEquals(new java.sql.Timestamp(time.getTimeInMillis()),
      inlineEntity.getProperty("PropertyTimeOfDay").getPrimitiveValue().toValue());
}
 
Example 18
Source File: APIBasicDesignTestITCase.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void createDelete() {
  // Create order ....
  final Order order = getContainer().newEntityInstance(Order.class);
  order.setOrderID(1105);

  final Calendar orderDate = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  orderDate.clear();
  orderDate.set(2011, 3, 4, 16, 3, 57);
  order.setOrderDate(new Timestamp(orderDate.getTimeInMillis()));

  order.setShelfLife(BigDecimal.ZERO);

  final PrimitiveCollection<BigDecimal> osl = getContainer().newPrimitiveCollection(BigDecimal.class);
  osl.add(BigDecimal.TEN.negate());
  osl.add(BigDecimal.TEN);

  order.setOrderShelfLifes(osl);

  getContainer().getOrders().add(order);
  getContainer().flush();

  Order actual = getContainer().getOrders().getByKey(1105);
  assertNull(actual.getOrderID());

  actual.load();
  assertEquals(1105, actual.getOrderID(), 0);
  assertEquals(orderDate.getTimeInMillis(), actual.getOrderDate().getTime());
  assertEquals(BigDecimal.ZERO, actual.getShelfLife());
  assertEquals(2, actual.getOrderShelfLifes().size());

  service.getContext().detachAll();

  // (1) Delete by key (see EntityCreateTestITCase)
  getContainer().getOrders().delete(1105);
  assertNull(getContainer().getOrders().getByKey(1105));

  service.getContext().detachAll(); // detach to show the second delete case

  // (2) Delete by object (see EntityCreateTestITCase)
  getContainer().getOrders().delete(getContainer().getOrders().getByKey(1105));
  assertNull(getContainer().getOrders().getByKey(1105));

  // (3) Delete by invoking delete method on the object itself
  service.getContext().detachAll(); // detach to show the third delete case
  getContainer().getOrders().getByKey(1105).delete();
  assertNull(getContainer().getOrders().getByKey(1105));

  getContainer().flush();

  service.getContext().detachAll();
  try {
    getContainer().getOrders().getByKey(1105).load();
    fail();
  } catch (IllegalArgumentException e) {
    // Test
  }
  service.getContext().detachAll(); // avoid influences
}
 
Example 19
Source File: TestHDFSEventSink.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
@Test
public void testSimpleAppend() throws InterruptedException,
    LifecycleException, EventDeliveryException, IOException {

  LOG.debug("Starting...");
  final String fileName = "FlumeData";
  final long rollCount = 5;
  final long batchSize = 2;
  final int numBatches = 4;
  String newPath = testPath + "/singleBucket";
  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", newPath);
  context.put("hdfs.filePrefix", fileName);
  context.put("hdfs.rollCount", String.valueOf(rollCount));
  context.put("hdfs.batchSize", String.valueOf(batchSize));

  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 < numBatches; 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);
  verifyOutputSequenceFiles(fs, conf, dirPath.toUri().getPath(), fileName, bodies);
}
 
Example 20
Source File: DaylightSavingTest.java    From spliceengine with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Strip away the time component from a {@code java.util.Date} and return
 * it as a {@code java.sql.Date}, so that it can be compared with a date
 * value returned by Derby. Derby will set the time component of the date
 * value to 00:00:00.0, so let's do the same here.
 *
 * @param date the date whose time component to strip away
 * @param cal the calendar used to store the date in the database originally
 * @return a date value that represents the same day as {@code date} in the
 * calendar {@code cal}, but with the time component normalized to
 * 00:00:00.0
 */
private static Date stripTime(java.util.Date date, Calendar cal) {
    cal.clear();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return new Date(cal.getTimeInMillis());
}