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

The following examples show how to use java.util.GregorianCalendar#getInstance() . 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: HolidaySpecialHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculate date of easter
 *
 * @param year year to calculate date of easter
 * @return Easter date
 */
private static Calendar getEasterDate(int year) {
    int a = year % 19;
    int b = year / 100;
    int c = year % 100;
    int d = b / 4;
    int e = b % 4;
    int f = (b + 8) / 25;
    int g = (b - f + 1) / 3;
    int h = (19 * a + b - d - g + 15) % 30;
    int i = c / 4;
    int k = c % 4;
    int l = (32 + 2 * e + 2 * i - h - k) % 7;
    int m = (a + 11 * h + 22 * l) / 451;
    int n = (h + l - 7 * m + 114) / 31;
    int p = (h + l - 7 * m + 114) % 31;
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.clear();
    calendar.set(year, n - 1, p + 1);
    return calendar;
}
 
Example 2
Source File: DateTimeParamTest.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Test
public void testStringParam() throws UnsupportedEncodingException, ParseException
{
    DateTimeParam dateTimeParam = new DateTimeParam( EXAMPLE_DATE_TIME );
    assertEquals( EXAMPLE_DATE, dateTimeParam.getDateString() );
    assertEquals( EXAMPLE_TIME, dateTimeParam.getTimeString() );

    Calendar result = GregorianCalendar.getInstance();
    result.setTime( dateTimeParam.getDate() );
    assertEquals( 2015, result.get( Calendar.YEAR ) );
    assertEquals( 10, result.get( Calendar.MONTH ));
    assertEquals( 30, result.get( Calendar.DAY_OF_MONTH ) );
    assertEquals( 23, result.get( Calendar.HOUR_OF_DAY ) );
    assertEquals( 48, result.get( Calendar.MINUTE ) );
    assertEquals( 21, result.get( Calendar.SECOND ) );
}
 
Example 3
Source File: Util.java    From maximorestclient with Apache License 2.0 6 votes vote down vote up
public static String stringValue(Object o) throws DatatypeConfigurationException, UnsupportedEncodingException
{
	if(o instanceof Date)
	{
        TimeZone timeZone = TimeZone.getDefault();
        GregorianCalendar gc = (GregorianCalendar)GregorianCalendar.getInstance(timeZone);
        gc.setTime((Date)o);

		return "\""+javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(gc).toXMLFormat()+"\"";
	}
	else if(o instanceof Number)
	{
		return ""+ o;
	}
	else if(o instanceof Boolean){
		return (o == null)?"null":o.toString();
	}
	else{
		return "\""+(String)o+"\"";
	}
}
 
Example 4
Source File: Utils.java    From Doradus with Apache License 2.0 5 votes vote down vote up
static public String currentGMTDateTime()
{
    TimeZone gmtTZ = TimeZone.getTimeZone("Europe/London");
    Calendar gmtCalendar = GregorianCalendar.getInstance();
    gmtCalendar.setTimeZone(gmtTZ);
    Date date = gmtCalendar.getTime();
    return date.toString();
}
 
Example 5
Source File: Shark.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
@Override
public double getPredisposition() throws Exception {

	Calendar date = GregorianCalendar.getInstance();
	if (date.get(Calendar.MONTH) == Calendar.AUGUST) {
		return 0.15;
	} else {
		return 0;
	}
}
 
Example 6
Source File: EmvUtils.java    From bankomatinfos with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param days
 *            number of days after September 02, 1975 (what happened on this
 *            day?)
 * @return
 */
public static Calendar getDayFromQuickLogEntry(int days) {
	Calendar logDay = GregorianCalendar.getInstance();
	logDay.set(Calendar.DAY_OF_MONTH, 2);
	logDay.set(Calendar.MONTH, Calendar.SEPTEMBER);
	logDay.set(Calendar.YEAR, 1975);
	logDay.add(Calendar.DAY_OF_YEAR, days);
	return logDay;
}
 
Example 7
Source File: RangerTimeOfDayMatcher.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isMatched(RangerAccessRequest request) {
	
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> RangerTimeOfDayMatcher.isMatched(" + request + ")");
	}

	boolean matched = true;
	if (_allowAny) {
		LOG.debug("isMatched: allowAny flag is true.  Matched!");
	} else if (request == null) {
		LOG.warn("isMatched: Unexpected: Request is null!  Implicitly matched!");
	} else if (request.getAccessTime() == null) {
		LOG.warn("isMatched: Unexpected: Accesstime on the request is null!  Implicitly matched!");
	} else {
		Date date = request.getAccessTime();
		Calendar calendar = GregorianCalendar.getInstance();
		calendar.setTime(date);
		int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
		int minutes = calendar.get(Calendar.MINUTE);
		if (! durationMatched(_durations, hourOfDay, minutes)) {
			matched = false;

			if (LOG.isDebugEnabled()) {
				LOG.debug("isMatched: None of the durations contains this hour of day[" + hourOfDay + "] and minutes[" + minutes + "]");
			}
		}
	}
	
	if(LOG.isDebugEnabled()) {
		LOG.debug("<== RangerTimeOfDayMatcher.isMatched(" + request+ "): " + matched);
	}

	return matched;
}
 
Example 8
Source File: YarnQueuesUtils.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * By default influxdb returns datetime in format yyyy-MM-ddTHH:mm:ssZ and
 * it is also UTC Time. So in this method we convert the datetime in local
 * time by adding offset (difference between local time and offset time) and
 * return the datetime in milliseconds.
 * 
 * @param original
 * @return
 * @throws ParseException
 */
public long getFormattedDate(String original) throws ParseException {
	original = original.replace(T, SPACE).replace(Z, EMPTY_STRING);
	DateFormat format = new SimpleDateFormat(YYYY_MM_DD_space_HH_MM_SS);
	Date date = format.parse(original);

	// Calculating timeoffset
	TimeZone timezone = TimeZone.getDefault();
	Calendar calender = GregorianCalendar.getInstance(timezone);

	return (date.getTime() + timezone.getOffset(calender.getTimeInMillis()));
}
 
Example 9
Source File: JSONTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static String getCurrentTimezoneOffset() {

        TimeZone tz = TimeZone.getDefault();
        Calendar cal = GregorianCalendar.getInstance(tz, Locale.ROOT);
        int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

        String offset = String.format(Locale.ROOT,"%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
        offset = (offsetInMillis >= 0 ? "+" : "-") + offset;

        return offset;
    }
 
Example 10
Source File: EquipmentLoanOrReturnDocumentRule.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Implementation of the rule that if a document has a valid expect loan date and loan return date, the both dates should come
 * before the 2 years limit.
 *
 * @param equipmentLoanOrReturnDocument the equipmentLoanOrReturn document to be validated
 * @return boolean false if the expect loan date or loan return date is not before the 2 years limit.
 */
protected boolean validateLoanDate(EquipmentLoanOrReturnDocument equipmentLoanOrReturnDocument) {
    boolean valid = true;
    Date loanDate = KfsDateUtils.clearTimeFields(equipmentLoanOrReturnDocument.getLoanDate());
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(loanDate);
    cal.add(Calendar.YEAR, 2);
    Date maxDate = new Date(cal.getTime().getTime());

    // Loan can not be before today
    Date loanReturnDate = equipmentLoanOrReturnDocument.getLoanReturnDate();
    if (equipmentLoanOrReturnDocument.isNewLoan() && loanDate.before(KfsDateUtils.clearTimeFields(new java.util.Date()))) {
        GlobalVariables.getMessageMap().putError(KFSConstants.DOCUMENT_PROPERTY_NAME + "." + CamsPropertyConstants.EquipmentLoanOrReturnDocument.LOAN_DATE, CamsKeyConstants.EquipmentLoanOrReturn.ERROR_INVALID_LOAN_DATE);
    }

    // expect return date must be >= loan date and within 2 years limit
    Date expectReturnDate = equipmentLoanOrReturnDocument.getExpectedReturnDate();
    if (expectReturnDate != null) {
        KfsDateUtils.clearTimeFields(expectReturnDate);
        if (expectReturnDate.before(loanDate)) {
            valid &= false;
            GlobalVariables.getMessageMap().putError(KFSConstants.DOCUMENT_PROPERTY_NAME + "." + CamsPropertyConstants.EquipmentLoanOrReturnDocument.EXPECTED_RETURN_DATE, CamsKeyConstants.EquipmentLoanOrReturn.ERROR_INVALID_EXPECTED_RETURN_DATE);
        }
        if (maxDate.before(expectReturnDate)) {
            valid &= false;
            GlobalVariables.getMessageMap().putError(KFSConstants.DOCUMENT_PROPERTY_NAME + "." + CamsPropertyConstants.EquipmentLoanOrReturnDocument.EXPECTED_RETURN_DATE, CamsKeyConstants.EquipmentLoanOrReturn.ERROR_INVALID_EXPECTED_MAX_DATE);
        }
    }

    // loan return date must be >= loan date and within 2 years limit
    if (loanReturnDate != null) {
        KfsDateUtils.clearTimeFields(loanReturnDate);
        if (loanDate.after(loanReturnDate) || maxDate.before(loanReturnDate)) {
            valid &= false;
            GlobalVariables.getMessageMap().putError(KFSConstants.DOCUMENT_PROPERTY_NAME + "." + CamsPropertyConstants.EquipmentLoanOrReturnDocument.LOAN_RETURN_DATE, CamsKeyConstants.EquipmentLoanOrReturn.ERROR_INVALID_LOAN_RETURN_DATE);
        }
    }

    return valid;
}
 
Example 11
Source File: DateUtil.java    From common-utils with GNU General Public License v2.0 5 votes vote down vote up
public static Date getYearBegin(final Date date) {
    if (date == null) {
        return null;
    }

    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.MONTH, 0);
    cal.set(Calendar.DATE, 1);

    return cal.getTime();
}
 
Example 12
Source File: CalenderConverterFactoryTest.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testConversionCurrentDate() throws ValueConverterException {
    CalendarConverterFactory factory = new CalendarConverterFactory();
    Converter converter = factory.getConverterForType(Calendar.class);

    Calendar calendar = GregorianCalendar.getInstance();
    Object converted = converter.convertToDolphin(calendar);
    Assert.assertNotNull(converted);
    Assert.assertEquals(((Calendar)converter.convertFromDolphin(converted)).getTime(), calendar.getTime());
}
 
Example 13
Source File: DateUtil.java    From common-utils with GNU General Public License v2.0 5 votes vote down vote up
public static Date getYearEnd(final Date date) {
    if (date == null) {
        return null;
    }

    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.MONTH, 11);

    return getEndOfMonth(cal.getTime());
}
 
Example 14
Source File: TestKarl.java    From evosql with Apache License 2.0 5 votes vote down vote up
/**
 * @param p_connection
 * @throws SQLException
 */
private static void doUpdateInsertDeleteWaehler(Connection p_connection)
throws SQLException {

    System.out.println("UPDATE WAEHLER START ...");

    PreparedStatement p = p_connection.prepareStatement(
        "UPDATE WAEHLER SET AUSTRITTSDATUM=? WHERE NAME=?");

    p.setDate(1, null);
    p.setString(2, "Muster1");
    p.execute();
    p.close();
    System.out.println("END UPDATE WAEHLER");
    System.out.println("INSERT INTO WAEHLER START ...");

    p = p_connection.prepareStatement(
        "INSERT INTO WAEHLER (NAME, AUSTRITTSDATUM) VALUES (?,?)");

    Calendar cal = GregorianCalendar.getInstance();

    p.setString(1, "Muster3");
    p.setDate(2, new Date(cal.getTimeInMillis()), cal);
    p.execute();
    p.close();
    System.out.println("END INSERT INTO WAEHLER");
    System.out.println("DELETE FROM WAEHLER START ...");

    p = p_connection.prepareStatement(
        "DELETE FROM WAEHLER WHERE NAME = ?");

    p.setString(1, "Muster2");
    p.execute();
    p.close();
    System.out.println("END DELETE FROM WAEHLER");
}
 
Example 15
Source File: TimeComponents.java    From adhan-java with MIT License 5 votes vote down vote up
public Date dateComponents(Date date) {
  Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
  calendar.setTime(date);
  calendar.set(Calendar.HOUR_OF_DAY, 0);
  calendar.set(Calendar.MINUTE, minutes);
  calendar.set(Calendar.SECOND, seconds);
  calendar.add(Calendar.HOUR_OF_DAY, hours);
  return calendar.getTime();
}
 
Example 16
Source File: Spider.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
@Override
public double getPredisposition() throws Exception {

	Calendar date = GregorianCalendar.getInstance();
	if (date.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
		return 0.3;
	} else {
		return 0;
	}
}
 
Example 17
Source File: Shark.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
@Override
public double getPredisposition() throws Exception {

	Calendar date = GregorianCalendar.getInstance();
	if (date.get(Calendar.MONTH) == Calendar.AUGUST) {
		return 0.15;
	} else {
		return 0;
	}
}
 
Example 18
Source File: Spider.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
@Override
public double getPredisposition() throws Exception {

	Calendar date = GregorianCalendar.getInstance();
	if (date.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
		return 0.3;
	} else {
		return 0;
	}
}
 
Example 19
Source File: DocumentManagerImpl.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Ticket createDownloadTicket(long docId, String suffix, Integer expireHours, Date expireDate,
		Integer maxDownloads, String urlPrefix, DocumentHistory transaction) throws Exception {
	assert (transaction.getUser() != null);

	Document document = documentDAO.findById(docId);
	if (document == null)
		throw new Exception("Unexisting document");

	if (!folderDAO.isDownloadEnabled(document.getFolder().getId(), transaction.getUserId()))
		throw new RuntimeException("You don't have the download permission");

	Ticket ticket = prepareTicket(docId, transaction.getUser());
	ticket.setSuffix(suffix);
	ticket.setEnabled(1);
	ticket.setMaxCount(maxDownloads);

	Calendar cal = GregorianCalendar.getInstance();
	if (expireDate != null) {
		cal.setTime(expireDate);
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		ticket.setExpired(cal.getTime());
	} else if (expireHours != null) {
		cal.add(Calendar.HOUR_OF_DAY, expireHours.intValue());
		ticket.setExpired(cal.getTime());
	} else {
		cal.add(Calendar.HOUR_OF_DAY, config.getInt("ticket.ttl"));
		ticket.setExpired(cal.getTime());
	}

	transaction.setEvent(DocumentEvent.DTICKET_CREATED.toString());
	transaction.setSessionId(transaction.getSessionId());

	ticketDAO.store(ticket, transaction);

	// Try to clean the DB from old tickets
	ticketDAO.deleteExpired();

	ticket.setUrl(composeTicketUrl(ticket, urlPrefix));

	return ticket;
}
 
Example 20
Source File: BasicTestCase.java    From snowcast with Apache License 2.0 4 votes vote down vote up
private SnowcastEpoch buildEpochFromCalendar() {
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.set(2014, 0, 1, 0, 0, 0);
    return SnowcastEpoch.byCalendar(calendar);
}