Java Code Examples for java.util.Calendar

The following examples show how to use java.util.Calendar. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
public static int getMonthFromDate(Date date) {

		int month = 0;

		if (date != null) {
			Calendar calendar = Calendar.getInstance();

			calendar.setTime(date);
			month += calendar.get(Calendar.MONTH);

//			calendar.setTime(date);
//			month = calendar.get(Calendar.MONTH);
//			return month;
		} else {
			month += 1;
		}

		return month;
	}
 
Example 2
Source Project: elepy   Source File: Revisions.java    License: Apache License 2.0 6 votes vote down vote up
public void createRevision(String revisionName,
                           RevisionType revisionType,
                           String userId,
                           String schemaPath,
                           Object snapshot) throws JsonProcessingException {

    final var revision = new Revision();

    revision.setSchemaPath(schemaPath);
    revision.setUserId(userId);
    revision.setRevisionType(revisionType);
    revision.setRevisionName(revisionName);
    revision.setRecordSnapshot(objectMapper.writeValueAsString(snapshot));

    revision.setRevisionNumber(0);
    revision.setTimestamp(Calendar.getInstance().getTime());


}
 
Example 3
public static int getDayFromDate(Date date) {

		int day = 0;

		if (date != null) {
			Calendar calendar = Calendar.getInstance();

			calendar.setTime(date);
			day += calendar.get(Calendar.DAY_OF_MONTH);

//			calendar.setTime(date);
//			day = calendar.get(Calendar.DAY_OF_MONTH);
//			return day;
		} else {
			day += 1;
		}

		return day;
	}
 
Example 4
Source Project: BotLibre   Source File: Utils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static String displayDate(Date date) {
	if (date == null) {
		return "";
	}
	StringWriter writer = new StringWriter();
	Calendar today = Calendar.getInstance();
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(date);
	if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR)
			&& calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
		writer.write("Today");
	} else if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR)
			&& calendar.get(Calendar.DAY_OF_YEAR) == (today.get(Calendar.DAY_OF_YEAR) - 1)) {
		writer.write("Yesterday");
	} else {
		writer.write(calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US));
		writer.write(" ");
		writer.write(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
		if (calendar.get(Calendar.YEAR) != today.get(Calendar.YEAR)) {
			writer.write(" ");
			writer.write(String.valueOf(calendar.get(Calendar.YEAR)));
		}
	}
	
	return writer.toString();
}
 
Example 5
Source Project: fabric-net-server   Source File: DateUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 返回日期中的指定部分--YYYY 年份,MM 月份,DD 天,HH 小时 MI 分 SS 秒
 *
 * @param date
 *            date日期
 * @param type
 *            日期中的指定部分
 *
 * @return 日期中的指定部分值
 */
public int getDatePart(Date date, DatePartType type) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	switch (type) {
	case Year:
		return cal.get(Calendar.YEAR);
	case Month:
		return cal.get(Calendar.MONTH);
	case Day:
		return cal.get(Calendar.DAY_OF_MONTH);
	case Hour:
		return cal.get(Calendar.HOUR_OF_DAY);
	case Minute:
		return cal.get(Calendar.MINUTE);
	case Second:
		return cal.get(Calendar.SECOND);
	default:
		return 0;
	}
}
 
Example 6
public void start() {
    particles.clear();
    if (Build.VERSION.SDK_INT >= 18) {
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }
    started = true;
    startedFall = false;
    fallingDownCount = 0;
    speedCoef = 1.0f;
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int month = calendar.get(Calendar.MONTH);
    isFebruary14 = month == 1 && (BuildVars.DEBUG_PRIVATE_VERSION || day == 14);
    if (isFebruary14) {
        loadHeartDrawables();
    }
    for (int a = 0; a < particlesCount; a++) {
        particles.add(createParticle(false));
    }
    invalidate();
}
 
Example 7
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    mCalendarCurrentTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
    mCalendarCurrentTime.set(Calendar.MINUTE, minute);

    String myFormatTime = ((FormElementPickerTime) mFormElement).getTimeFormat(); // custom format
    SimpleDateFormat sdfTime = new SimpleDateFormat(myFormatTime, Locale.US);

    String currentValue = mFormElement.getValue();
    String newValue = sdfTime.format(mCalendarCurrentTime.getTime());

    // trigger event only if the value is changed
    if (!currentValue.equals(newValue)) {
        mReloadListener.updateValue(mPosition, newValue);
    }
}
 
Example 8
Source Project: youqu_master   Source File: TimeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 描述:获取本周的某一天.
 *
 * @param format        the format
 * @param calendarField the calendar field
 * @return String String类型日期时间
 */
private static String getDayOfWeek(String format, int calendarField) {
    String strDate = null;
    try {
        Calendar c = new GregorianCalendar();
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
        int week = c.get(Calendar.DAY_OF_WEEK);
        if (week == calendarField) {
            strDate = mSimpleDateFormat.format(c.getTime());
        } else {
            int offectDay = calendarField - week;
            if (calendarField == Calendar.SUNDAY) {
                offectDay = 7 - Math.abs(offectDay);
            }
            c.add(Calendar.DATE, offectDay);
            strDate = mSimpleDateFormat.format(c.getTime());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return strDate;
}
 
Example 9
Source Project: astor   Source File: DateUtilsRoundingTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests DateUtils.round()-method with Calendar.DATE
 * Includes rounding the extremes of one day 
 * Includes rounding to January 1
 * 
 * @throws Exception
 * @since 3.0
 */
public void testRoundDate() throws Exception {
    final int calendarField = Calendar.DATE;
    Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
    Date minDate, maxDate;

    roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
    roundedDownDate = targetDateDate;
    lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //round to January 1
    minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000");
    maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999");
    roundToJanuaryFirst(minDate, maxDate, calendarField);
}
 
Example 10
Source Project: WheelViewDemo   Source File: DateTimeWheelDialog.java    License: Apache License 2.0 6 votes vote down vote up
private void initAreaDate() {
    int startYear = startCalendar.get(Calendar.YEAR);
    int endYear = endCalendar.get(Calendar.YEAR);
    int startMonth = startCalendar.get(Calendar.MONTH) + 1;
    int startDay = startCalendar.get(Calendar.DAY_OF_MONTH);
    int startHour = startCalendar.get(Calendar.HOUR_OF_DAY);
    int startMinute = startCalendar.get(Calendar.MINUTE);

    yearItems = updateItems(DateItem.TYPE_YEAR, startYear, endYear);
    monthItems = updateItems(DateItem.TYPE_MONTH, startMonth, MAX_MONTH);
    int dayActualMaximum = startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    dayItems = updateItems(DateItem.TYPE_DAY, startDay, dayActualMaximum);
    hourItems = updateItems(DateItem.TYPE_HOUR, startHour, MAX_HOUR);
    minuteItems = updateItems(DateItem.TYPE_MINUTE, startMinute, MAX_MINUTE);
    yearWheelItemView.setItems(yearItems);
    monthWheelItemView.setItems(monthItems);
    dayWheelItemView.setItems(dayItems);
    hourWheelItemView.setItems(hourItems);
    minuteWheelItemView.setItems(minuteItems);
}
 
Example 11
Source Project: jsmpp   Source File: RelativeTimeFormatterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(groups = "checkintest")
public void formatRelativeTimeHours() {
  GregorianCalendar smscDate = new GregorianCalendar(TimeZone.getTimeZone("America/Denver"));

  GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("America/Denver"));
  date.setTimeInMillis(smscDate.getTimeInMillis());
  date.add(Calendar.HOUR_OF_DAY, 16);
  assertEquals(relativeTimeFormatter.format(date, smscDate), "000000160000000R");
}
 
Example 12
private ChargingData createChargingData() throws Exception {
    ChargingData chargingData = new ChargingData();
    chargingData.setTransactionId(1L);
    chargingData.setAddress("");
    chargingData.setCurrency("EUR");
    chargingData.setCustomerKey(Long.valueOf(1L));
    chargingData.setEmail("email");
    chargingData.setExternalIdentifier("externalidentifier");
    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, 1970);
    c.set(Calendar.MONTH, 0);
    c.set(Calendar.DAY_OF_MONTH, 2);
    chargingData.setPeriodEndTime(c.getTime());
    chargingData.setPeriodStartTime(c.getTime());
    chargingData.setSellerKey(Long.valueOf(2L));

    chargingData.setGrossAmount(BigDecimal.valueOf(1226));
    chargingData.setNetAmount(BigDecimal.valueOf(1030));
    chargingData.setNetDiscount(BigDecimal.ZERO);
    chargingData.setVatAmount(BigDecimal.valueOf(196));
    chargingData.setVat("");

    chargingData.setSubscriptionId("sub");
    chargingData.setPon("12345");

    chargingData.getPriceModelData().add(
            new PriceModelData(1, 1259622000000L, 1262300400000L,
                    BigDecimal.valueOf(1000)));
    chargingData.getPriceModelData().add(
            new PriceModelData(2, 1259622000000L, 1262300400000L,
                    BigDecimal.valueOf(2000)));

    return chargingData;
}
 
Example 13
Source Project: ApplicationPower   Source File: DateTimeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将时间设置位当年第一天,并且将时分秒全部置0
 *
 * @param millis long
 * @return long
 */
public static long setToFirstDayOfCurrentYear(long millis) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(millis);
    cal.set(Calendar.DAY_OF_YEAR, 1);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis();
}
 
Example 14
Source Project: sinavi-jfw   Source File: Dates.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * その月の最後の日を取得します。
 * @param date 基準となる日付
 * @return その月の最後の日
 */
public static int lastDay(Date date) {
    if (date == null) return -1;
    Calendar calendar = Calendar.getInstance();
    calendar.setLenient(true);
    calendar.setTime(date);
    calendar.add(Calendar.MONTH, 1);
    calendar.add(Calendar.DAY_OF_MONTH, -1);
    return calendar.get(Calendar.DAY_OF_MONTH);
}
 
Example 15
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException
{
	checkNotClosed();
	try
	{
		preparedStatement.setTime(parameterIndex, x, cal);
	}
	catch (SQLException sqlException)
	{
		pooledCassandraConnection.statementErrorOccurred(preparedStatement, sqlException);
		throw sqlException;
	}
}
 
Example 16
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    Calendar alarmtime = Calendar.getInstance();
    alarmtime.set(year, monthOfYear, dayOfMonth, hourOfDay, minute);

    if (hasAlarm) {
        //Update the current alarm
        DbAccess.updateNotificationTime(getBaseContext(), notification_id, alarmtime.getTimeInMillis());
    } else {
        //create new alarm
        notification_id = (int) (long) DbAccess.addNotification(getBaseContext(), id, alarmtime.getTimeInMillis());
    }
    //Store a reference for the notification in the database. This is later used by the service.

    //Create the intent that is fired by AlarmManager
    Intent i = new Intent(this, NotificationService.class);
    i.putExtra(NotificationService.NOTIFICATION_ID, notification_id);

    PendingIntent pi = PendingIntent.getService(this, notification_id, i, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmtime.getTimeInMillis(), pi);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, alarmtime.getTimeInMillis(), pi);
    }
    Toast.makeText(getApplicationContext(), String.format(getString(R.string.toast_alarm_scheduled), dayOfMonth + "." + (monthOfYear+1) + "." + year + " " + hourOfDay + ":" + String.format("%02d",minute)), Toast.LENGTH_SHORT).show();
    loadActivity(false);
}
 
Example 17
Source Project: ECG-Viewer   Source File: Minute.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the last millisecond of the minute.
 *
 * @param calendar  the calendar / timezone (<code>null</code> not
 *     permitted).
 *
 * @return The last millisecond.
 *
 * @throws NullPointerException if <code>calendar</code> is
 *     <code>null</code>.
 */
@Override
public long getLastMillisecond(Calendar calendar) {
    int year = this.day.getYear();
    int month = this.day.getMonth() - 1;
    int d = this.day.getDayOfMonth();

    calendar.clear();
    calendar.set(year, month, d, this.hour, this.minute, 59);
    calendar.set(Calendar.MILLISECOND, 999);

    return calendar.getTimeInMillis();
}
 
Example 18
Source Project: SEAL-Demo   Source File: DateUtil.java    License: MIT License 5 votes vote down vote up
/**
 * @return the phases of the day from Calendar
 */
public static String getDayPhases(Context context,Calendar calendar) {
    int hours = calendar.get(Calendar.HOUR_OF_DAY);

    if (hours >= 1 && hours <= 12) {
        return context.getString(R.string.morning_string);
    } else if (hours >= 12 && hours <= 16) {
        return context.getString(R.string.afternoon_string);
    } else if (hours >= 16 && hours <= 21) {
        return context.getString(R.string.evening_string);
    } else if (hours >= 21 && hours <= 24) {
        return context.getString(R.string.night_string);
    }
    return "";
}
 
Example 19
Source Project: gemfirexd-oss   Source File: DVDStoreResultSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Timestamp getTimestamp(int columnIndex, Calendar cal)
    throws SQLException {
  if (columnIndex > 0 && columnIndex <= this.numColumns) {
    try {
      final DataValueDescriptor dvd;
      if (this.currentRowDVDs != null) {
        dvd = this.currentRowDVDs[columnIndex - 1];
      }
      else if (this.pvs != null) {
        dvd = this.pvs.getParameter(columnIndex - 1);
      }
      else {
        throw noCurrentRow();
      }
      if (dvd != null && !dvd.isNull()) {
        this.wasNull = false;
        if (cal == null) {
          cal = getCal();
        }
        return dvd.getTimestamp(cal);
      }
      else {
        this.wasNull = true;
        return null;
      }
    } catch (StandardException se) {
      throw Util.generateCsSQLException(se);
    }
  }
  else {
    throw invalidColumnException(columnIndex);
  }
}
 
Example 20
Source Project: maintain   Source File: PaymentTool.java    License: MIT License 5 votes vote down vote up
public static void generateCbecMessageCiq(Object object, String dir, String backDir) {
		if (null == object) {
			return;
		}
		JAXBContext context = null;
		Marshaller marshaller = null;
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		SimpleDateFormat sdfToday = new SimpleDateFormat("yyyyMMdd");
		String fileName = "FILE_PAYMENT_" + sdf.format(calendar.getTime());
		File cbecMessage = new File(dir + fileName + ".xml");
		File backCbecMessage = new File(backDir + sdfToday.format(calendar.getTime()) + "/" + fileName + ".xml");
		File backDirFile = new File(backDir + sdfToday.format(calendar.getTime()));
		try {
			context = JAXBContext.newInstance(object.getClass());
			marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
			
			if (!backDirFile.exists()) {
				backDirFile.mkdir();
			}
			
			marshaller.marshal(object, backCbecMessage);
			marshaller.marshal(object, cbecMessage);
		} catch (Exception e) {
			e.printStackTrace();
			logger.equals(e);
		}
	}
 
Example 21
Source Project: cloudstack   Source File: UsageServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException {
    Integer interval = cmd.getInterval();
    if (interval != null && interval > 0 ) {
        String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString());
        if (jobExecTime != null ) {
            String[] segments = jobExecTime.split(":");
            if (segments.length == 2) {
                String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString());
                if (timeZoneStr == null) {
                    timeZoneStr = "GMT";
                }
                TimeZone tz = TimeZone.getTimeZone(timeZoneStr);
                Calendar cal = Calendar.getInstance(tz);
                cal.setTime(new Date());
                long curTS = cal.getTimeInMillis();
                cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0]));
                cal.set(Calendar.MINUTE, Integer.parseInt(segments[1]));
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                long execTS = cal.getTimeInMillis();
                s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS);
                // Let's avoid cleanup when job runs and around a 15 min interval
                if (Math.abs(curTS - execTS) < 15 * 60 * 1000) {
                    return false;
                }
            }
        }
        _usageDao.removeOldUsageRecords(interval);
    } else {
        throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0");
    }
    return true;
}
 
Example 22
Source Project: ApplicationPower   Source File: DateTimeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据时间获取是周几(中国化)
 *
 * @param ms long
 * @return int
 */
public static int getDayOfWeek(long ms) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(ms);
    int a = cal.get(Calendar.DAY_OF_WEEK);
    if (a >= 2) {
        return a - 1;
    } else {
        return 7;
    }
}
 
Example 23
private Date getFirstDayOfYear(Date date) {
    Calendar calendar = getCalendar();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    calendar.set(Calendar.DAY_OF_YEAR, 1);
    return calendar.getTime();
}
 
Example 24
Source Project: super-csv   Source File: WritingFeaturesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConverterSupport() throws IOException {
	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.YEAR, 1999);
	calendar.set(Calendar.MONTH, 6);
	calendar.set(Calendar.DAY_OF_MONTH, 12);
	
	FeatureBean character = new FeatureBean("John", "Connor", 16);
	character.setSavings(new BigDecimal(6.65));
	character.setBirthDate(calendar.getTime());
	
	String[] mapping = { "lastName", "firstName", "age", "birthDate", "savings" };
	DecimalFormat formatter = new DecimalFormat();
	formatter.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance());
	CellProcessor[] processors = { new NotNull(), new NotNull(), new NotNull(), new FmtDate("yyyy-MM-dd"),
		new FmtNumber(formatter) };
	
	StringWriter writer = new StringWriter();
	CsvPreference customPreference = new Builder('"', '|', "\r\n").build();
	CsvBeanWriter beanWriter = new CsvBeanWriter(writer, customPreference);
	beanWriter.write(character, mapping, processors);
	beanWriter.close();
	
	String csv = writer.toString();
	Assert.assertNotNull(csv);
	Assert.assertEquals("Connor|John|16|1999-07-12|" + formatter.format(character.getSavings()) + "\r\n", csv);
}
 
Example 25
Source Project: cql_engine   Source File: FhirModelResolver.java    License: Apache License 2.0 5 votes vote down vote up
protected DateTime toDateTime(BaseDateTimeType value, Integer calendarConstant) {
    Calendar calendar = this.getCalendar(value);

    TimeZone tz = calendar.getTimeZone() == null ? TimeZone.getDefault() : calendar.getTimeZone();
    ZoneOffset zoneOffset = tz.toZoneId().getRules().getStandardOffset(calendar.toInstant());
    switch (calendarConstant) {
        case Calendar.YEAR: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR)
        );
        case Calendar.MONTH: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1
        );
        case Calendar.DAY_OF_MONTH: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)
        );
        case Calendar.HOUR_OF_DAY: return new DateTime(
            TemporalHelper.zoneToOffset(zoneOffset),
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY)
        );
        case Calendar.MINUTE: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                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)
        );
        case Calendar.SECOND: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                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)
        );
        case Calendar.MILLISECOND: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                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), calendar.get(Calendar.MILLISECOND)
        );
        default: throw new InvalidPrecision(String.format("Invalid temporal precision %s", calendarConstant));
    }
}
 
Example 26
@Test
public void dateParseLocNominal() {
	try {
		Locale locale = new Locale("en");
		Date date = new Date(707781600000L);
		Calendar cal = Calendar.getInstance(locale);
		cal.setTime(date);

		Expression expression = getExpressionWithFunctionContext("date_parse_loc(\"6/6/92\", \"en\")");
		assertEquals(ExpressionType.DATE, expression.getExpressionType());
		assertEquals(cal.getTime(), expression.evaluateDate());
	} catch (ExpressionException e) {
		fail(e.getMessage());
	}
}
 
Example 27
Source Project: scava   Source File: TaskCheckExecutor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public Date dateToDay(Date date) {
	Calendar cal = Calendar.getInstance(); // locale-specific
	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());
}
 
Example 28
Source Project: JavaMainRepo   Source File: Spider.java    License: 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 29
Source Project: lams   Source File: FastDateFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Formats a <code>Date</code>, <code>Calendar</code> or
 * <code>Long</code> (milliseconds) object.</p>
 * 
 * @param obj  the object to format
 * @param toAppendTo  the buffer to append to
 * @param pos  the position - ignored
 * @return the buffer passed in
 */
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    if (obj instanceof Date) {
        return format((Date) obj, toAppendTo);
    } else if (obj instanceof Calendar) {
        return format((Calendar) obj, toAppendTo);
    } else if (obj instanceof Long) {
        return format(((Long) obj).longValue(), toAppendTo);
    } else {
        throw new IllegalArgumentException("Unknown class: " +
            (obj == null ? "<null>" : obj.getClass().getName()));
    }
}
 
Example 30
public void testFactory_fromDateFields_beforeYearZero3() throws Exception {
    GregorianCalendar cal = new GregorianCalendar(3, 1, 3, 4, 5, 6);
    cal.set(Calendar.ERA, GregorianCalendar.BC);
    cal.set(Calendar.MILLISECOND, 7);
    LocalDate expected = new LocalDate(-2, 2, 3);
    assertEquals(expected, LocalDate.fromDateFields(cal.getTime()));
}