Java Code Examples for java.util.GregorianCalendar#setTime()

The following examples show how to use java.util.GregorianCalendar#setTime() . 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: LiteralsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.rdf4j.model.util.Literals#createLiteralOrFail(org.eclipse.rdf4j.model.ValueFactory, java.lang.Object)}
 * .
 */
@Test
public void testCreateLiteralOrFailObjectXMLGregorianCalendar() throws Exception {

	GregorianCalendar c = new GregorianCalendar();
	c.setTime(new Date());
	try {
		Object obj = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
		Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj);
		assertNotNull(l);
		assertEquals(l.getDatatype(), XMLSchema.DATETIME);
		// TODO check lexical value?
	} catch (DatatypeConfigurationException e) {
		e.printStackTrace();
		fail("Could not instantiate javax.xml.datatype.DatatypeFactory");
	}

}
 
Example 2
Source File: CalendarRegression.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * GregorianCalendar handling of Dates Long.MIN_VALUE and Long.MAX_VALUE is
 * confusing; unless the time zone has a raw offset of zero, one or the
 * other of these will wrap.  We've modified the test given in the bug
 * report to therefore only check the behavior of a calendar with a zero raw
 * offset zone.
 */
public void Test4145158() {
    GregorianCalendar calendar = new GregorianCalendar();

    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));

    calendar.setTime(new Date(Long.MIN_VALUE));
    int year1 = calendar.get(YEAR);
    int era1 = calendar.get(ERA);

    calendar.setTime(new Date(Long.MAX_VALUE));
    int year2 = calendar.get(YEAR);
    int era2 = calendar.get(ERA);

    if (year1 == year2 && era1 == era2) {
        errln("Fail: Long.MIN_VALUE or Long.MAX_VALUE wrapping around");
    }
}
 
Example 3
Source File: ScriptHelper.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Parse a given date string to a GregorianCalendar
 *
 * @param dateValue
 * @param datePattern
 * @return
 */
public GregorianCalendar parseDate(final String dateValue, final String datePattern) {

	/*
	 * **************************************************
	 *   IMPORTANT  IMPORTANT    IMPORTANT    IMPORTANT
	 * **************************************************
	 *
	 * DO NOT REMOVE METHOD OR CHANGE SIGNATURE!!!
	 */

	try {
		final GregorianCalendar returnValue = new GregorianCalendar();
		final Date parsedDate = new SimpleDateFormat(datePattern).parse(dateValue);
		returnValue.setTime(parsedDate);
		return returnValue;
	} catch (final ParseException e) {
		return null;
	}
}
 
Example 4
Source File: AppleUtil.java    From AppleCommander with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a ProDOS date into the buffer.
 */
public static void setProdosDate(byte[] buffer, int offset, Date date) {
	int day = 0;
	int month = 0;
	int year = 0;
	int minute = 0;
	int hour = 0;
	if (date != null) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		day = gc.get(Calendar.DAY_OF_MONTH);
		month = gc.get(Calendar.MONTH) + 1;
		year = gc.get(Calendar.YEAR);
		minute = gc.get(Calendar.MINUTE);
		hour = gc.get(Calendar.HOUR_OF_DAY);
		if (year >= 2000) {
			year -= 2000;
		} else {
			year -= 1900;
		}
	}
	int ymd = ((year & 0x7f) << 9) | ((month & 0xf) << 5) | (day & 0x1f);
	int hm = ((hour & 0x1f) << 8) | (minute & 0x3f);
	setWordValue(buffer, offset, ymd);
	setWordValue(buffer, offset+2, hm);
}
 
Example 5
Source File: TimeUtil.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取今年是哪一年
 * @return
 */
public static Integer getNowYear() {
    Date date = new Date();
    GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
    gc.setTime(date);
    return Integer.valueOf(gc.get(1));
}
 
Example 6
Source File: SealedProcessor.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static XMLGregorianCalendar getXMLGregorianCalendar (Date dateValue) {
	XMLGregorianCalendar dateTime = null;
	try {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(dateValue);
		DatatypeFactory df;
		df = DatatypeFactory.newInstance();
		dateTime = df.newXMLGregorianCalendar(calendar);
	} catch (DatatypeConfigurationException e) {
		//printStackTrace(e,startTimeStamp,procedure,info);
	}
	return dateTime;
}
 
Example 7
Source File: DatatypeTest.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testForValue() throws Exception {
	checkForValue(-1);
	checkForValue(1);
	checkForValue(2l);
	checkForValue(-2l);
	checkForValue(123123123123111232l);
	checkForValue(3.0d);
	checkForValue(4.0f);
	checkForValue((short)5);
	checkForValue((short)2000);
	checkForValue((short)-5);
	checkForValue((byte)6);
	checkForValue(true);
	checkForValue(URI.create("http://www.example.org"));
	checkForValue("test");
	checkForValue(new String[]{"test","test2"});
	checkForValue(BigDecimal.ONE);
	checkForValue(BigInteger.ONE);
	checkForValue(BigInteger.ZERO);
	checkForValue(BigInteger.valueOf(-1));
	checkForValue(new QName("http://www.example.org#","name"));
	checkForValue(DatatypeFactory.newInstance().newDuration(23));
	GregorianCalendar gc=new GregorianCalendar();
	gc.setTime(new Date());
	checkForValue(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
}
 
Example 8
Source File: DayModel_GetColumnsForEventsTest.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
private Date time(int hour, int minutes) {
	GregorianCalendar gc = new GregorianCalendar();
	gc.setTime(new Date());
	gc.set(Calendar.HOUR_OF_DAY, hour);
	gc.set(Calendar.MINUTE, minutes);
	return gc.getTime();
}
 
Example 9
Source File: DateUtil.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean isValidSendDate( Date sendDate) {
	// Create the calendar object for comparison
    GregorianCalendar now = new GregorianCalendar();
    GregorianCalendar sendDateCalendar = new GregorianCalendar();

    // Set the time of the test-calendar
    sendDateCalendar.setTime( sendDate);

    // Move "current time" 5 minutes into future, so we get a 5 minute fairness period
    now.add( Calendar.MINUTE, -5);
    
    // Do the hard work!
    return now.before( sendDateCalendar);
}
 
Example 10
Source File: DefaultJobManager.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected JobEntity internalCreateLockedAsyncJob(ExecutionEntity execution, boolean exclusive) {
  JobEntity asyncJob = processEngineConfiguration.getJobEntityManager().create();
  fillDefaultAsyncJobInfo(asyncJob, execution, exclusive);
  
  GregorianCalendar gregorianCalendar = new GregorianCalendar();
  gregorianCalendar.setTime(processEngineConfiguration.getClock().getCurrentTime());
  gregorianCalendar.add(Calendar.MILLISECOND, getAsyncExecutor().getAsyncJobLockTimeInMillis());
  asyncJob.setLockExpirationTime(gregorianCalendar.getTime());
  asyncJob.setLockOwner(getAsyncExecutor().getLockOwner());
  
  return asyncJob;
}
 
Example 11
Source File: AppleUtil.java    From AppleCommander with GNU General Public License v2.0 5 votes vote down vote up
/**
  * Set a Pascal data to the buffer.<br>
  * Bits 0-3: month (1-12)<br>
  * Bits 4-8: day (1-31)<br>
  * Bits 9-15: year (0-99)
  */
public static void setPascalDate(byte[] buffer, int offset, Date date) {
	GregorianCalendar gc = new GregorianCalendar();
	gc.setTime(date);
	int month = gc.get(Calendar.MONTH) + 1;
	int day = gc.get(Calendar.DAY_OF_MONTH);
	int year = gc.get(Calendar.YEAR) % 100;
	int pascalDate = (month & 0x000f)
		| ((day << 4) & 0x01f0)
		| ((year << 9) & 0xfe00);
	setWordValue(buffer, offset, pascalDate);
}
 
Example 12
Source File: ExecutionEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void scheduleAtomicOperationAsync(AtomicOperation executionOperation) {
    JobEntity message = new JobEntity();
    message.setJobType(Job.JOB_TYPE_MESSAGE);
    message.setRevision(1);
    message.setExecution(this);
    message.setExclusive(getActivity().isExclusive());
    message.setJobHandlerType(AsyncContinuationJobHandler.TYPE);
    // At the moment, only AtomicOperationTransitionCreateScope can be performed asynchronously,
    // so there is no need to pass it to the handler

    ProcessEngineConfiguration processEngineConfig = Context.getCommandContext().getProcessEngineConfiguration();

    if (processEngineConfig.getAsyncExecutor().isActive()) {
        GregorianCalendar expireCal = new GregorianCalendar();
        expireCal.setTime(processEngineConfig.getClock().getCurrentTime());
        expireCal.add(Calendar.SECOND, processEngineConfig.getLockTimeAsyncJobWaitTime());
        message.setLockExpirationTime(expireCal.getTime());
    }

    // Inherit tenant id (if applicable)
    if (getTenantId() != null) {
        message.setTenantId(getTenantId());
    }

    callJobProcessors(JobProcessorContext.Phase.BEFORE_CREATE, message, Context.getProcessEngineConfiguration());
    Context.getCommandContext().getJobEntityManager().send(message);
}
 
Example 13
Source File: AcquireTimerJobsCmd.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void lockJob(CommandContext commandContext, TimerJobEntity job, int lockTimeInMillis) {
  
  // This will trigger an optimistic locking exception when two concurrent executors 
  // try to lock, as the revision will not match.
  
  GregorianCalendar gregorianCalendar = new GregorianCalendar();
  gregorianCalendar.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());
  gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis);
  job.setLockOwner(asyncExecutor.getLockOwner());
  job.setLockExpirationTime(gregorianCalendar.getTime());
}
 
Example 14
Source File: DateUtil.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
/**
 * <pre>
 * 描述:间隔指定天数后日期(例如:每3天)
 * 作者:ZhangYi
 * 时间:2016年5月5日 下午4:29:07
 * 参数:(参数列表)
 * @param dateTime	指定日期
 * @param interval	间隔天数
 * @return
 * </pre>
 */
public static Date handleDateTimeByDay(Date dateTime, int interval) {
	try {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(dateTime);
		calendar.add(Calendar.DAY_OF_MONTH, interval);
		dateTime = calendar.getTime();
	} catch (Exception e) {
		logger.error("--间隔指定天数后日期异常!", e);
	}
	return dateTime;
}
 
Example 15
Source File: TestUtils.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static boolean verifyDate(int expYear, int expMonth, int expDay, int expHour, int expMin, int expSec, Date value) {
   GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
   gc.setTime(value);
   // 2015-04-23T18:23:09.123
   return ((expYear == gc.get(Calendar.YEAR)) &&
         (expMonth - 1 == gc.get(Calendar.MONTH)) &&
         (expDay == gc.get(Calendar.DAY_OF_MONTH)) &&
         (expHour == gc.get(Calendar.HOUR_OF_DAY)) &&
         (expMin == gc.get(Calendar.MINUTE)) &&
         (expSec == gc.get(Calendar.SECOND)));
}
 
Example 16
Source File: DateUtils.java    From teaching with Apache License 2.0 4 votes vote down vote up
public static int getYear() {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(getDate());
    return calendar.get(Calendar.YEAR);
}
 
Example 17
Source File: Date.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public static GregorianCalendar createCalendar(long timeMS) {
	GregorianCalendar G = new GregorianCalendar();
	G.setTime(new java.util.Date(timeMS));
	return G;
}
 
Example 18
Source File: DateUtilities.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date getDateOfHoursAgo(Date initDate, int hoursAgo) {
GregorianCalendar returnDate = new GregorianCalendar();
returnDate.setTime(initDate);
returnDate.add(Calendar.HOUR, -hoursAgo);
return returnDate.getTime();
  }
 
Example 19
Source File: ExtractRowsViaTemplate.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
public void setup() throws ParseException, IOException {
  // insert a sample MarkLogic template which can extract fields from the
  // sample data below
  ObjectMapper mapper = new ObjectMapper()
    .configure(Feature.ALLOW_SINGLE_QUOTES, true);
  docMgr.writeAs(templateUri, mapper.readTree(
    "{ 'template':{ 'description':'test template', 'context':'/firstName', " +
    "    'rows':[ { 'schemaName':'employee', 'viewName':'employee'," +
    "      'columns':[ { 'name':'firstName', 'scalarType':'string', 'val':'.' }," +
    "                  { 'name':'salary', 'scalarType':'int', 'nullable':true," +
    "                    'val':'max(../salaries/salary)'}" +
    " ] } ] } }"));

  // insert some sample documents
  String[][] employees = new String[][] {
    {"1", "1990-10-04", "Alice", "Edward", "FEMALE", "2012-04-05", "70675"},
    {"2", "1992-12-23", "Bob", "Miller", "MALE", "2010-06-01", "98023"},
    {"3", "1985-11-30", "Gerard", "Steven", "MALE", "2011-07-29", "87455"},
    {"4", "1970-01-08", "Evelyn", "Erick", "FEMALE", "2012-08-24", "62444"},
    {"5", "1978-05-14", "Daniel", "Washington", "MALE", "2007-02-17", "68978,76543,86732"},
    {"6", "1989-07-19", "Eve", "Alfred", "FEMALE", "2009-08-14", "70987,79083"},
    {"7", "1990-09-29", "Rachel", "Fisher", "FEMALE", "2015-01-01", "50678"},
    {"8", "1987-10-26", "Bruce", "Wayne", "MALE", "2010-04-09", "99873,106742"},
    {"9", "1992-11-25", "Thomas", "Crook", "MALE", "2013-07-07", "79003"},
    {"10", "1994-12-04", "Diana", "Trevor", "FEMALE", "2016-09-23", "67893,67993"}
  };
  for ( String[] employee : employees ) {
    Employee newEmployee = new Employee();
    newEmployee.setEmployeeId(Integer.parseInt(employee[0]));
    GregorianCalendar bday = new GregorianCalendar();
    bday.setTime(df.parse(employee[1]));
    newEmployee.setBirthDate(bday);
    newEmployee.setFirstName(employee[2]);
    newEmployee.setLastName(employee[3]);
    newEmployee.setGender(Gender.valueOf(employee[4]));
    ArrayList<Salary> salaries = new ArrayList<>();
    for ( String salary : employee[6].split(",") ) {
      Salary newSalary = new Salary();
      newSalary.setSalary(Integer.parseInt(salary));
      salaries.add(newSalary);
    }
    newEmployee.setSalaries(salaries.toArray(new Salary[salaries.size()]));
    docMgr.writeAs("/employees/" + employee[0] + ".json", newEmployee);
  }
}
 
Example 20
Source File: XElement.java    From open-ig with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Convert the given date to string.
 * Always contains the milliseconds and timezone.
 * @param date the date, not null
 * @return the formatted date
 */
public static String formatDateTime(Date date) {
	StringBuilder b = new StringBuilder(24);
	
	GregorianCalendar cal = XSD_CALENDAR.get();
	cal.setTime(date);
	
	int value;
	
	// Year-Month-Day
	value = cal.get(GregorianCalendar.YEAR);
	b.append(value);
	b.append('-');
	value = cal.get(GregorianCalendar.MONTH) + 1;
	if (value < 10) {
		b.append('0');
	}
	b.append(value);
	b.append('-');
	value = cal.get(GregorianCalendar.DATE);
	if (value < 10) {
		b.append('0');
	}
	b.append(value);
	
	b.append('T');
	// hour:minute:second:milliseconds
	value = cal.get(GregorianCalendar.HOUR_OF_DAY);
	if (value < 10) {
		b.append('0');
	}
	b.append(value);
	b.append(':');
	value = cal.get(GregorianCalendar.MINUTE);
	if (value < 10) {
		b.append('0');
	}
	b.append(value);
	b.append(':');
	value = cal.get(GregorianCalendar.SECOND);
	if (value < 10) {
		b.append('0');
	}
	b.append(value);
	b.append('.');
	
	value = cal.get(GregorianCalendar.MILLISECOND);
	// add leading zeros if needed
	if (value < 100) {
		b.append('0');
	}
	if (value < 10) {
		b.append('0');
	}
	b.append(value);
	
	value = cal.get(GregorianCalendar.DST_OFFSET) + cal.get(GregorianCalendar.ZONE_OFFSET);
	
	if (value == 0) {
		b.append('Z');
	} else {
		if (value < 0) {
			b.append('-');
			value = -value;
		} else {
			b.append('+');
		}
		int hour = value / 3600000;
		int minute = value / 60000 % 60;
		if (hour < 10) {
			b.append('0');
		}
		b.append(hour);
		b.append(':');
		if (minute < 10) {
			b.append('0');
		}
		b.append(minute);
	}
	
	
	return b.toString();
}