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

The following examples show how to use java.util.GregorianCalendar#set() . 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: TestLocalDateTime_Basics.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testToDate_winter() {
    LocalDateTime base = new LocalDateTime(2005, 1, 9, 10, 20, 30, 40, COPTIC_PARIS);
    
    Date test = base.toDate();
    check(base, 2005, 1, 9, 10, 20, 30, 40);
    
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.clear();
    gcal.set(Calendar.YEAR, 2005);
    gcal.set(Calendar.MONTH, Calendar.JANUARY);
    gcal.set(Calendar.DAY_OF_MONTH, 9);
    gcal.set(Calendar.HOUR_OF_DAY, 10);
    gcal.set(Calendar.MINUTE, 20);
    gcal.set(Calendar.SECOND, 30);
    gcal.set(Calendar.MILLISECOND, 40);
    assertEquals(gcal.getTime(), test);
}
 
Example 2
Source File: CMClientFixture.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
public void refresh(Date day, CalendarableItem[] controls) {
	if (controls.length != data[getOffset(day)].length) {
		throw new RuntimeException("Number of elements to fill != amount of data we've got");
	}
	int dateOffset = getOffset(day);
	for (int i = 0; i < controls.length; i++) {
		String text = data[dateOffset][i];
		if (text.startsWith("1")) {
			controls[i].setText(text);
			controls[i].setAllDayEvent(true);
		} else {
			controls[i].setText(text);
			controls[i].setAllDayEvent(false);
			GregorianCalendar gc = new GregorianCalendar();
			gc.setTime(new Date());
			gc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(text));
			controls[i].setStartTime(gc.getTime());
		}
	}
}
 
Example 3
Source File: GMTDateformatter.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * @param string
 * @return
 */
public static GregorianCalendar parseGregorian(String formattedDate)
{
	if ( formattedDate == null || formattedDate.length() != 17 ) {
		return null;
	}
	GregorianCalendar gc =  new GregorianCalendar(gmt);
	int year = Integer.parseInt(formattedDate.substring(0,4));
	int month = Integer.parseInt(formattedDate.substring(4,6));
	int day = Integer.parseInt(formattedDate.substring(6,8));
	int hour = Integer.parseInt(formattedDate.substring(8,10));
	int minute = Integer.parseInt(formattedDate.substring(10,12));
	int second = Integer.parseInt(formattedDate.substring(12,14));
	int millis = Integer.parseInt(formattedDate.substring(14));
	gc.set(Calendar.YEAR, year);
	gc.set(Calendar.MONTH, month-1);
	gc.set(Calendar.DATE, day);
	gc.set(Calendar.HOUR_OF_DAY, hour);
	gc.set(Calendar.MINUTE, minute);
	gc.set(Calendar.SECOND, second);
	gc.set(Calendar.MILLISECOND, millis);
	return gc;
}
 
Example 4
Source File: DateFormatterTest.java    From jsmpp with Apache License 2.0 6 votes vote down vote up
@Test(groups = "checkintest")
public void formatAbsoluteDateRussia() {
  TimeFormatter timeFormatter = new AbsoluteTimeFormatter();

  GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("Asia/Yekaterinburg"), new Locale("ru", "RU"));
  date.set(Calendar.YEAR, 2013);
  date.set(Calendar.MONTH, Calendar.JANUARY);
  date.set(Calendar.DAY_OF_MONTH, 1);
  date.set(Calendar.HOUR_OF_DAY, 1);
  date.set(Calendar.MINUTE, 0);
  date.set(Calendar.SECOND, 0);
  date.set(Calendar.MILLISECOND, 0);

  assertEquals(timeFormatter.format(date), "130101010000024+");

  date.set(Calendar.MONTH, Calendar.JULY);

  // we have the same offset because of the absent of daylight saving time
  assertEquals(timeFormatter.format(date), "130701010000024+");
}
 
Example 5
Source File: FreeMarkerModelLuceneFunctionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test generation of lucene date ranges
 *
 */
public void testLuceneDateRangeFunctionToDate()
{
    GregorianCalendar cal = new GregorianCalendar();
    cal.set(Calendar.YEAR, 2001);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    String isoStartDate = ISO8601DateFormat.format(cal.getTime());
    cal.add(Calendar.DAY_OF_MONTH, 4);
    String isoEndDate = ISO8601DateFormat.format(cal.getTime());
    String template = "${luceneDateRange(\""+isoStartDate+"\", \""+isoEndDate+"\")}";
    FreeMarkerWithLuceneExtensionsModelFactory mf = new FreeMarkerWithLuceneExtensionsModelFactory();
    mf.setServiceRegistry(serviceRegistry);
    String result = serviceRegistry.getTemplateService().processTemplateString("freemarker", template, mf.getModel());
    assertEquals(result, "["+isoStartDate+" TO "+isoEndDate+"]");
}
 
Example 6
Source File: Bug6178071.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    GregorianCalendar cal = new GregorianCalendar(2004, JANUARY, 1);
    cal.set(HOUR, 1);
    if (cal.get(HOUR_OF_DAY) != 1 ||
        cal.get(HOUR) != 1 || cal.get(AM_PM) != AM) {
        throw new RuntimeException("Unexpected hour of day: " + cal.getTime());
    }

    // Test case for 6440854
    GregorianCalendar gc = new GregorianCalendar(2006,5,16);
    gc.setLenient(false);
    gc.set(HOUR_OF_DAY, 10);
    // The following line shouldn't throw an IllegalArgumentException.
    gc.get(YEAR);
}
 
Example 7
Source File: MonthCalendarSnippet.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 8
Source File: TestScenarioCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create the root context object, an Inventor instance. Non-qualified property
 * and method references will be resolved against this context object.
 * @param testContext the evaluation context in which to set the root object
 */
private static void setupRootContextObject(StandardEvaluationContext testContext) {
	GregorianCalendar c = new GregorianCalendar();
	c.set(1856, 7, 9);
	Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");
	tesla.setPlaceOfBirth(new PlaceOfBirth("SmilJan"));
	tesla.setInventions(new String[] { "Telephone repeater", "Rotating magnetic field principle",
			"Polyphase alternating-current system", "Induction motor", "Alternating-current power transmission",
			"Tesla coil transformer", "Wireless communication", "Radio", "Fluorescent lights" });
	testContext.setRootObject(tesla);
}
 
Example 9
Source File: GregorianCalendarTester.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void test_setMonth() {
    GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
    GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
    GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
    calendarExpected.set(Calendar.MONTH, 3);
    Date expectedDate = calendarExpected.getTime();
    assertEquals(expectedDate, calendarDemo.setMonth(calendarActual, 3));
}
 
Example 10
Source File: SPATest.java    From solarpositioning with MIT License 5 votes vote down vote up
@Test
public void testOtherSpaExampleSunriseTransitSet() {
    GregorianCalendar time = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    time.set(2004, Calendar.DECEMBER, 4, 12, 30, 30);

    GregorianCalendar[] res = SPA.calculateSunriseTransitSet(time, -35.0, 0, 0);

    DateFormat df = getDateFormat(time);

    assertEquals("2004-12-04T04:38:57+0000", df.format(res[0].getTime()));
    assertEquals("2004-12-04T19:02:01+0000", df.format(res[2].getTime())); // SPA paper has 19:02:02.5
}
 
Example 11
Source File: ZipEntry.java    From dexdiff with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the last modification time of this {@code android.ZipEntry}.
 * 
 * @return the last modification time as the number of milliseconds since Jan. 1, 1970.
 */
public long getTime() {
    if (time != -1) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(1980 + ((modDate >> 9) & 0x7f), ((modDate >> 5) & 0xf) - 1, modDate & 0x1f, (time >> 11) & 0x1f,
                (time >> 5) & 0x3f, (time & 0x1f) << 1);
        return cal.getTime().getTime();
    }
    return -1;
}
 
Example 12
Source File: MobileServiceQueryTests.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
private static Date getUTCDate(int year, int month, int day, int hour, int minute, int second) {
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("utc"));
    int dateMonth = month - 1;
    calendar.set(year, dateMonth, day, hour, minute, second);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}
 
Example 13
Source File: SPATest.java    From solarpositioning with MIT License 5 votes vote down vote up
@Test
public void testDSTonDayBerlin() {
    GregorianCalendar time = new GregorianCalendar(TimeZone.getTimeZone("Europe/Berlin"));
    time.set(2016, Calendar.MARCH, 27, 12, 0, 0);

    GregorianCalendar[] res = SPA.calculateSunriseTransitSet(time, 52.33, 13.3, 68);

    DateFormat df = getDateFormat(time);

    assertEquals("2016-03-27T06:52:19+0200", df.format(res[0].getTime())); // NOAA: 06:52 (no seconds given)
    assertEquals("2016-03-27T13:12:02+0200", df.format(res[1].getTime())); // NOAA: 13:12:01
    assertEquals("2016-03-27T19:32:49+0200", df.format(res[2].getTime())); // NOAA: 19:33 (no seconds given)
}
 
Example 14
Source File: RelativeTimeFormatterTest.java    From jsmpp with Apache License 2.0 5 votes vote down vote up
@Test(groups = "checkintest")
public void formatRelativeDateDifferentTimeZone() {
  GregorianCalendar smscDate = new GregorianCalendar(TimeZone.getTimeZone("America/Denver"));
  smscDate.set(2014, Calendar.JANUARY, 2, 23, 15, 16);
  GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
  date.set(2014, Calendar.JANUARY, 2, 23, 15, 16);
  assertEquals(relativeTimeFormatter.format(date, smscDate), "000000010000000R");
}
 
Example 15
Source File: TestMonthDay_Constructors.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testFactory_FromDateFields() throws Exception {
    GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6);
    cal.set(Calendar.MILLISECOND, 7);
    MonthDay expected = new MonthDay(2, 3);
    assertEquals(expected, MonthDay.fromDateFields(cal.getTime()));
    try {
        MonthDay.fromDateFields(null);
        fail();
    } catch (IllegalArgumentException ex) {}
}
 
Example 16
Source File: DateConverter.java    From PdfBox-Android with Apache License 2.0 5 votes vote down vote up
static GregorianCalendar newGreg()
{
    GregorianCalendar retCal = new GregorianCalendar(Locale.ENGLISH);
    retCal.setTimeZone(new SimpleTimeZone(0, "UTC"));
    retCal.setLenient(false);
    retCal.set(Calendar.MILLISECOND, 0);
    return retCal;
}
 
Example 17
Source File: TimeScalesTest.java    From diirt with MIT License 5 votes vote down vote up
@Test
public void createReferencesBoundary9() {
//test two references, doesn't fit perfectly, but start happens
//to be a perfect multiple of the time period, and so does the time interval
GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 );
cal.set( GregorianCalendar.MILLISECOND , 996 );
Instant start = cal.getTime().toInstant();
TimeInterval timeInterval = TimeInterval.between( start , start.plus( Duration.ofMillis( 8 ) ) );
List<Instant> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) );
assertThat( references.size() , equalTo(3) );
assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 996 ) ) );
assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) );
assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 4 ) ) );
}
 
Example 18
Source File: CalendarTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test the mapping between millis and fields.  For the purposes
 * of this test, we don't care about timezones and week data
 * (first day of week, minimal days in first week).
 */
@SuppressWarnings("deprecation")
public void TestMapping() {
    TimeZone saveZone = TimeZone.getDefault();
    int[] DATA = {
        // Julian#   Year      Month    DOM   JULIAN:Year  Month,   DOM
        2440588,     1970,    JANUARY,   1,    1969,     DECEMBER,  19,
        2415080,     1900,      MARCH,   1,    1900,     FEBRUARY,  17,
        2451604,     2000,   FEBRUARY,  29,    2000,     FEBRUARY,  16,
        2452269,     2001,   DECEMBER,  25,    2001,     DECEMBER,  12,
        2416526,     1904,   FEBRUARY,  15,    1904,     FEBRUARY,   2,
        2416656,     1904,       JUNE,  24,    1904,         JUNE,  11,
        1721426,        1,    JANUARY,   1,       1,      JANUARY,   3,
        2000000,      763,  SEPTEMBER,  18,     763,    SEPTEMBER,  14,
        4000000,     6239,       JULY,  12,    6239,          MAY,  28,
        8000000,    17191,   FEBRUARY,  26,   17190,      OCTOBER,  22,
       10000000,    22666,   DECEMBER,  20,   22666,         JULY,   5};

    try {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        Date PURE_GREGORIAN = new Date(Long.MIN_VALUE);
        Date PURE_JULIAN = new Date(Long.MAX_VALUE);
        GregorianCalendar cal = new GregorianCalendar();
        for (int i = 0; i < DATA.length; i += 7) {
            int julian = DATA[i];
            int year = DATA[i + 1];
            int month = DATA[i + 2];
            int dom = DATA[i + 3];
            int year2, month2, dom2;
            long millis = ((long) julian - EPOCH_JULIAN) * ONE_DAY;
            String s;

            // Test Gregorian computation
            cal.setGregorianChange(PURE_GREGORIAN);
            cal.clear();
            cal.set(year, month, dom);
            long calMillis = cal.getTime().getTime();
            long delta = calMillis - millis;
            cal.setTime(new Date(millis));
            year2 = cal.get(YEAR);
            month2 = cal.get(MONTH);
            dom2 = cal.get(DAY_OF_MONTH);
            s = "G " + year + "-" + (month + 1 - JANUARY) + "-" + dom
                    + " => " + calMillis
                    + " (" + ((float) delta / ONE_DAY) + " day delta) => "
                    + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2;
            if (delta != 0 || year != year2 || month != month2
                    || dom != dom2) {
                errln(s + " FAIL");
            } else {
                logln(s);
            }

            // Test Julian computation
            year = DATA[i + 4];
            month = DATA[i + 5];
            dom = DATA[i + 6];
            cal.setGregorianChange(PURE_JULIAN);
            cal.clear();
            cal.set(year, month, dom);
            calMillis = cal.getTime().getTime();
            delta = calMillis - millis;
            cal.setTime(new Date(millis));
            year2 = cal.get(YEAR);
            month2 = cal.get(MONTH);
            dom2 = cal.get(DAY_OF_MONTH);
            s = "J " + year + "-" + (month + 1 - JANUARY) + "-" + dom
                    + " => " + calMillis
                    + " (" + ((float) delta / ONE_DAY) + " day delta) => "
                    + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2;
            if (delta != 0 || year != year2 || month != month2
                    || dom != dom2) {
                errln(s + " FAIL");
            } else {
                logln(s);
            }
        }

        cal.setGregorianChange(new Date(1582 - 1900, OCTOBER, 15));
        auxMapping(cal, 1582, OCTOBER, 4);
        auxMapping(cal, 1582, OCTOBER, 15);
        auxMapping(cal, 1582, OCTOBER, 16);
        for (int y = 800; y < 3000; y += 1 + 100 * Math.random()) {
            for (int m = JANUARY; m <= DECEMBER; ++m) {
                auxMapping(cal, y, m, 15);
            }
        }
    } finally {
        TimeZone.setDefault(saveZone);
    }
}
 
Example 19
Source File: DecoderUtils.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes the given string as a standard IMAP date-time.
 * 
 * @param chars
 *            standard IMAP date-time
 * @return <code>Date</code> with time component, not null
 * @throws DecodingException
 *             when this conversion fails
 */
public static LocalDateTime decodeDateTime(CharSequence chars) throws DecodingException {
    if (isDateTime(chars)) {
        char dayHigh = chars.charAt(0);
        char dayLow = chars.charAt(1);
        int day = decodeFixedDay(dayHigh, dayLow);

        char monthFirstChar = chars.charAt(3);
        char monthSecondChar = chars.charAt(4);
        char monthThirdChar = chars.charAt(5);
        int month = decodeMonth(monthFirstChar, monthSecondChar, monthThirdChar);

        char milleniumChar = chars.charAt(7);
        char centuryChar = chars.charAt(8);
        char decadeChar = chars.charAt(9);
        char yearChar = chars.charAt(10);
        int year = decodeYear(milleniumChar, centuryChar, decadeChar, yearChar);

        char zoneDeterminent = chars.charAt(21);
        char zoneDigitOne = chars.charAt(22);
        char zoneDigitTwo = chars.charAt(23);
        char zoneDigitThree = chars.charAt(24);
        char zoneDigitFour = chars.charAt(25);
        int offset = decodeZone(zoneDeterminent, zoneDigitOne, zoneDigitTwo, zoneDigitThree, zoneDigitFour);

        char hourHigh = chars.charAt(12);
        char hourLow = chars.charAt(13);
        int hour = applyHourOffset(offset, decodeNumber(hourHigh, hourLow));

        char minuteHigh = chars.charAt(15);
        char minuteLow = chars.charAt(16);
        int minute = applyMinuteOffset(offset, decodeNumber(minuteHigh, minuteLow));

        char secondHigh = chars.charAt(18);
        char secondLow = chars.charAt(19);
        int second = decodeNumber(secondHigh, secondLow);

        GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"), Locale.US);
        calendar.clear();
        calendar.set(year, month, day, hour, minute, second);
        return LocalDateTime.ofInstant(calendar.getTime().toInstant(), ZoneId.systemDefault());
    } else {
        final String message;
        if (chars == null) {
            message = "Expected a date-time but was nothing.";
        } else {
            message = new StringBuffer("Expected a date-time but was ").append(chars.toString()).toString();
        }

        throw new DecodingException(HumanReadableText.ILLEGAL_ARGUMENTS, message);
    }

}
 
Example 20
Source File: TestIsoChronoImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
@UseDataProvider("provider_rangeVersusCalendar")
public void test_DayOfWeek_IsoChronology_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals("Unexpected calendar type", cal.getCalendarType(), "gregory");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) {
        for (int minDays = 1; minDays <= 7; minDays++) {
            WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
            cal.setFirstDayOfWeek(Math.floorMod(firstDayOfWeek.getValue(), 7) + 1);
            cal.setMinimalDaysInFirstWeek(minDays);

            cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
            cal.set(Calendar.YEAR, isoDate.get(YEAR));
            cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
            cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

            // For every date in the range
            while (isoDate.isBefore(isoEndDate)) {
                assertEquals("Day mismatch in " + isoDate + ";  cal: " + cal,
                    isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH));
                assertEquals("Month mismatch in " + isoDate, isoDate.get(MONTH_OF_YEAR),
                    cal.get(Calendar.MONTH) + 1);
                assertEquals("Year mismatch in " + isoDate, isoDate.get(YEAR_OF_ERA),
                    cal.get(Calendar.YEAR));

                int jdow = Math.floorMod(cal.get(Calendar.DAY_OF_WEEK) - 2, 7) + 1;
                int dow = isoDate.get(weekDef.dayOfWeek());
                assertEquals("Calendar DayOfWeek does not match ISO DayOfWeek", jdow, dow);

                int jweekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
                int isoWeekOfMonth = isoDate.get(weekDef.weekOfMonth());
                assertEquals("Calendar WeekOfMonth does not match ISO WeekOfMonth",
                    jweekOfMonth, isoWeekOfMonth);

                int jweekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
                int weekOfYear = isoDate.get(weekDef.weekOfWeekBasedYear());
                assertEquals("GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear",
                    jweekOfYear, weekOfYear);

                int jWeekYear = cal.getWeekYear();
                int weekBasedYear = isoDate.get(weekDef.weekBasedYear());
                assertEquals("GregorianCalendar getWeekYear does not match YearOfWeekBasedYear",
                    jWeekYear, weekBasedYear);

                int jweeksInWeekyear = cal.getWeeksInWeekYear();
                int weeksInWeekBasedYear = (int)isoDate.range(weekDef.weekOfWeekBasedYear()).getMaximum();
                assertEquals("length of weekBasedYear", jweeksInWeekyear, weeksInWeekBasedYear);

                isoDate = isoDate.plus(1, ChronoUnit.DAYS);
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
    }
}