java.util.GregorianCalendar Java Examples

The following examples show how to use java.util.GregorianCalendar. 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: BluetoothBytesParserTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void setDateTimeTest() {
    BluetoothBytesParser parser = new BluetoothBytesParser();
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam"));
    long timestamp = 1578310812218L;
    calendar.setTimeInMillis(timestamp);

    parser.setDateTime(calendar);
    parser.setOffset(0);
    Date parsedDateTime = parser.getDateTime();
    assertEquals(7, parser.getValue().length);
    calendar.setTime(parsedDateTime);
    assertEquals(2020, calendar.get(GregorianCalendar.YEAR));
    assertEquals(1, calendar.get(GregorianCalendar.MONTH) + 1);
    assertEquals(6, calendar.get(GregorianCalendar.DAY_OF_MONTH));
    assertEquals(12, calendar.get(GregorianCalendar.HOUR_OF_DAY));
    assertEquals(40, calendar.get(GregorianCalendar.MINUTE));
    assertEquals(12, calendar.get(GregorianCalendar.SECOND));
}
 
Example #2
Source File: YearTest.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Some checks for the getFirstMillisecond(TimeZone) method.
 */
@Test
public void testGetFirstMillisecondWithCalendar() {
    Year y = new Year(2001);
    GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
    calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt"));
    assertEquals(978307200000L, y.getFirstMillisecond(calendar));

    // try null calendar
    boolean pass = false;
    try {
        y.getFirstMillisecond((Calendar) null);
    }
    catch (NullPointerException e) {
        pass = true;
    }
    assertTrue(pass);
}
 
Example #3
Source File: Bug8074791.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] arg) {
    int errors = 0;

    DateFormat df = DateFormat.getDateInstance(LONG, FINNISH);
    Date jan20 = new GregorianCalendar(2015, JANUARY, 20).getTime();
    String str = df.format(jan20).toString();
    // Extract the month name (locale data dependent)
    String month = str.replaceAll(".+\\s([a-z]+)\\s\\d+$", "$1");
    if (!month.equals(JAN_FORMAT)) {
        errors++;
        System.err.println("wrong format month name: got '" + month
                           + "', expected '" + JAN_FORMAT + "'");
    }

    SimpleDateFormat sdf = new SimpleDateFormat("LLLL", FINNISH); // stand-alone month name
    month = sdf.format(jan20);
    if (!month.equals(JAN_STANDALONE)) {
        errors++;
        System.err.println("wrong stand-alone month name: got '" + month
                           + "', expected '" + JAN_STANDALONE + "'");
    }

    if (errors > 0) {
        throw new RuntimeException();
    }
}
 
Example #4
Source File: RelativeDateFormat.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new instance.
 * 
 * @param baseMillis  the time zone (<code>null</code> not permitted).
 */
public RelativeDateFormat(long baseMillis) {
    super();        
    this.baseMillis = baseMillis;
    this.showZeroDays = false;
    this.showZeroHours = true;
    this.positivePrefix = "";
    this.dayFormatter = NumberFormat.getInstance();
    this.daySuffix = "d";
    this.hourSuffix = "h";
    this.minuteSuffix = "m";
    this.secondFormatter = NumberFormat.getNumberInstance();
    this.secondFormatter.setMaximumFractionDigits(3);
    this.secondFormatter.setMinimumFractionDigits(3);
    this.secondSuffix = "s";

    // we don't use the calendar or numberFormat fields, but equals(Object) 
    // is failing without them being non-null
    this.calendar = new GregorianCalendar();
    this.numberFormat = new DecimalFormat("0");    
}
 
Example #5
Source File: JRDataUtils.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static double getExcelSerialDayNumber(Date date, Locale locale, TimeZone timeZone)
{
	GregorianCalendar calendar = new GregorianCalendar(timeZone,locale);
	calendar.setTime(date);

	int year = calendar.get(Calendar.YEAR);
	int month = calendar.get(Calendar.MONTH); // starts from 0
	int day = calendar.get(Calendar.DAY_OF_MONTH);
	int hour = calendar.get(Calendar.HOUR_OF_DAY);
	int min = calendar.get(Calendar.MINUTE);
	int sec = calendar.get(Calendar.SECOND);
	int millis = calendar.get(Calendar.MILLISECOND);
	
	double result = getGregorianToJulianDay(year, month + 1, day) +
			(Math.floor(millis + 1000 * (sec + 60 * (min + 60 * hour)) + 0.5) / 86400000.0);	
	return (result - JULIAN_1900) + 1 + ((result > 2415078.5) ? 1 : 0);
}
 
Example #6
Source File: RelativeDateFormat.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param baseMillis  the time zone (<code>null</code> not permitted).
 */
public RelativeDateFormat(long baseMillis) {
    super();
    this.baseMillis = baseMillis;
    this.showZeroDays = false;
    this.showZeroHours = true;
    this.positivePrefix = "";
    this.dayFormatter = NumberFormat.getNumberInstance();
    this.daySuffix = "d";
    this.hourFormatter = NumberFormat.getNumberInstance();
    this.hourSuffix = "h";
    this.minuteFormatter = NumberFormat.getNumberInstance();
    this.minuteSuffix = "m";
    this.secondFormatter = NumberFormat.getNumberInstance();
    this.secondFormatter.setMaximumFractionDigits(3);
    this.secondFormatter.setMinimumFractionDigits(3);
    this.secondSuffix = "s";

    // we don't use the calendar or numberFormat fields, but equals(Object)
    // is failing without them being non-null
    this.calendar = new GregorianCalendar();
    this.numberFormat = new DecimalFormat("0");
}
 
Example #7
Source File: MillisecondTest.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Some checks for the getFirstMillisecond(TimeZone) method.
 */
@Test
public void testGetFirstMillisecondWithCalendar() {
    Millisecond m = new Millisecond(500, 55, 40, 2, 15, 4, 2000);
    GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
    calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt"));
    assertEquals(955766455500L, m.getFirstMillisecond(calendar));

    // try null calendar
    boolean pass = false;
    try {
        m.getFirstMillisecond((Calendar) null);
    }
    catch (NullPointerException e) {
        pass = true;
    }
    assertTrue(pass);
}
 
Example #8
Source File: dateTimeTokenizer.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private boolean processDate1Digit(java.util.GregorianCalendar _calendar, char[] _month, int _part1 ) {
	
	// convert the month characters to a numeric
  int month;
  if(realLocale == null)
    month = monthConverter.convertMonthToInt(_month);// returns month byte[] as an int index from 0;
  else
    month = monthConverter.convertMonthToInt(_month, new DateFormatSymbols(realLocale));

  if ( month == -1 ) return false;
  
  int defaultYear = _calendar.get( Calendar.YEAR );
  
  // now we need to figure out whether the numerical part represents the year or the day
  if (prelimDateCheck(_calendar, month + 1, _part1, defaultYear)){ // month/day
  	return setCalendar(_calendar, defaultYear, month, _part1); 
  }else if (prelimDateCheck(_calendar, 1, month + 1, _part1)){ // month/year
  	return setCalendar(_calendar, _part1, month, 1);
  }
	return false;
}
 
Example #9
Source File: SQLTime.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void setFrom(DataValueDescriptor theValue) throws StandardException {

		if (theValue instanceof SQLTime) {
			restoreToNull();

			SQLTime tvst = (SQLTime) theValue;
			encodedTime = tvst.encodedTime;
			encodedTimeFraction = tvst.encodedTimeFraction;

		}
        else
        {
            GregorianCalendar cal = ClientSharedData.getDefaultCleanCalendar();
			setValue(theValue.getTime( cal), cal);
        }
	}
 
Example #10
Source File: Vimshottari.java    From Astrosoft with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {

		Vimshottari v = new Vimshottari(300 + ( 59.00 / 60.00 ), new GregorianCalendar(1980, Calendar.DECEMBER, 11));
		//v.getDasa().get(Planet.Rahu).getSubDasas();
		//v.getDasa().get(Planet.Venus).getSubDasas().get(Planet.Venus).getSubDasas();
		//System.out.println(v);
		//System.out.println("Current:-> " + v.getCurrent());
		
		EnumMap<Planet, Dasa> dasa = v.getDasa();
		
		for(Planet p : Planet.dasaLords(v.getStartLord())){
			
			Dasa d = dasa.get(p);
			for(Dasa sb : d.subDasas()) {
				System.out.println(TableDataFactory.toCSV(v.getVimDasaTableData(sb),getVimDasaTableColumnMetaData()));
				System.out.println("**********************************************************");
			}
			System.out.println("---------------------------------------------------------");
		}
		
		//System.out.println(TableDataFactory.toCSV(v.getVimDasaTableData(),getVimDasaTableColumnMetaData()));
		
		//System.out.println(v.printDasaTree());
		
	}
 
Example #11
Source File: TestTemporalDistance.java    From ensemble-clustering with MIT License 6 votes vote down vote up
@Test
public void testOverlappingByDayInWeekRegions() {
	Date date1 = (new GregorianCalendar(2010, 01, 01)).getTime();
	Date date2 = new Date( date1.getTime() + MS_PER_WEEK );
	
	Date date3 = date2;
	Date date4 = new Date( date3.getTime() + MS_PER_WEEK );
	
	TemporalFeature t1 = new TemporalFeature();
	t1.setValue(date1, date2);
	
	TemporalFeature t2 = new TemporalFeature();
	t2.setValue(date3, date4);
	
	TemporalDistance d = new TemporalDistance(1);
	
	double distance = d.distance(t1, t2);
	double expected = 1.0 - (2.0 * MS_PER_DAY / (2.0 * MS_PER_WEEK));
	
	assertTrue(isEqual(distance, expected));
	distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2));
	assertTrue(isEqual(distance, expected));
}
 
Example #12
Source File: DateUtilsBasic.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 判断是否润年.
 * @param ddate
 *            	时间字符串, “yyyy-MM-dd” 格式
 * @return boolean<br>
 * 				true: ddate 表示的年份是闰年;
 * 				false: ddate 表示的年份不是闰年;
 */
public static boolean isLeapYear(String ddate) {

	/**
	 * 详细设计: 1.被400整除是闰年, 2不能被400整除,能被100整除不是闰年 3.不能被100整除,能被4整除则是闰年 4.不能被4整除不是闰年
	 */
	Date d = strToDate(ddate);
	GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
	gc.setTime(d);
	int year = gc.get(Calendar.YEAR);
	if ((year % 400) == 0) {
		return true;
	} else if (year % 100 == 0) {
		return false;
	} else {
		return ((year % 4) == 0);
	}
}
 
Example #13
Source File: Bug8074791.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] arg) {
    int errors = 0;

    DateFormat df = DateFormat.getDateInstance(LONG, FINNISH);
    Date jan20 = new GregorianCalendar(2015, JANUARY, 20).getTime();
    String str = df.format(jan20).toString();
    // Extract the month name (locale data dependent)
    String month = str.replaceAll(".+\\s([a-z]+)\\s\\d+$", "$1");
    if (!month.equals(JAN_FORMAT)) {
        errors++;
        System.err.println("wrong format month name: got '" + month
                           + "', expected '" + JAN_FORMAT + "'");
    }

    SimpleDateFormat sdf = new SimpleDateFormat("LLLL", FINNISH); // stand-alone month name
    month = sdf.format(jan20);
    if (!month.equals(JAN_STANDALONE)) {
        errors++;
        System.err.println("wrong stand-alone month name: got '" + month
                           + "', expected '" + JAN_STANDALONE + "'");
    }

    if (errors > 0) {
        throw new RuntimeException();
    }
}
 
Example #14
Source File: DEXService.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
private XMLGregorianCalendar toXMLCal(Calendar cal) {
	if (cal == null) {
		return null;
	}

	DatatypeFactory dtf = null;
	try {
		dtf = DatatypeFactory.newInstance();
	} catch (DatatypeConfigurationException e) {
		e.printStackTrace();
		return null;
	}

	GregorianCalendar gc = new GregorianCalendar();
	gc.setTimeInMillis(cal.getTimeInMillis());
	return dtf.newXMLGregorianCalendar(gc);
}
 
Example #15
Source File: Utils_Time.java    From AsteroidOSSync with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the current time as a byte array, useful for implementing {@link BleServices#currentTime()} for example.
 */
public static byte[] getCurrentTime()
{
	final byte[] time = new byte[10];
	final byte adjustReason = 0;
	GregorianCalendar timestamp = new GregorianCalendar();

	short year = (short) timestamp.get( Calendar.YEAR );
	final byte[] year_bytes = Utils_Byte.shortToBytes(year);
	Utils_Byte.reverseBytes(year_bytes);

	System.arraycopy(year_bytes, 0, time, 0, 2);

	time[2] = (byte)(timestamp.get( Calendar.MONTH ) + 1);
	time[3] = (byte)timestamp.get( Calendar.DAY_OF_MONTH );
	time[4] = (byte)timestamp.get( Calendar.HOUR_OF_DAY );
	time[5] = (byte)timestamp.get( Calendar.MINUTE );
	time[6] = (byte)timestamp.get( Calendar.SECOND );
	time[7] = (byte)timestamp.get( Calendar.DAY_OF_WEEK );
	time[8] = 0; // 1/256 of a second
	time[9] = adjustReason;

	return time;
}
 
Example #16
Source File: MonthTests.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * In Auckland, the end of Feb 2000 is java.util.Date(951,821,999,999L).
 * Use this to check the Month constructor.
 */
public void testDateConstructor2() {

    TimeZone zone = TimeZone.getTimeZone("Pacific/Auckland");
    Calendar c = new GregorianCalendar(zone);
    Month m1 = new Month(new Date(951821999999L), zone, 
    		Locale.getDefault());
    Month m2 = new Month(new Date(951822000000L), zone, 
    		Locale.getDefault());

    assertEquals(MonthConstants.FEBRUARY, m1.getMonth());
    assertEquals(951821999999L, m1.getLastMillisecond(c));

    assertEquals(MonthConstants.MARCH, m2.getMonth());
    assertEquals(951822000000L, m2.getFirstMillisecond(c));

}
 
Example #17
Source File: KmerStatSimulator.java    From MHAP with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public KmerStatSimulator() {
	if (false) {
		GregorianCalendar t = new GregorianCalendar();
		int t1 = t.get(Calendar.SECOND);
		int t2 = t.get(Calendar.MINUTE);
		int t3 = t.get(Calendar.HOUR_OF_DAY);
		int t4 = t.get(Calendar.DAY_OF_MONTH);
		int t5 = t.get(Calendar.MONTH);
		int t6 = t.get(Calendar.YEAR);
		seed = t6 + 65 * (t5 + 12 * (t4 + 31 * (t3 + 24 * (t2 + 60 * t1))));
	}

	generator = new Random(seed);
}
 
Example #18
Source File: Bug6178071.java    From openjdk-jdk8u 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 #19
Source File: DbxEntryTest.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void parseFile() throws Exception
{
    DbxEntry.File f = loadJsonResource(DbxEntry.Reader, "/file.json").asFile();
    assertEquals(f.path, "/Photos/Sample Album/Boston City Flow.jpg");
    assertEquals(f.numBytes, 339773);
    assertEquals(f.mightHaveThumbnail, true);
    assertEquals(f.rev, "400113f659");
    assertEquals(f.humanSize, "331.8 KB");

    GregorianCalendar c = new GregorianCalendar(2013, GregorianCalendar.APRIL, 11, 17, 5, 17);
    c.setTimeZone(TimeZone.getTimeZone("UTC"));
    assertEquals(f.lastModified, c.getTime());
}
 
Example #20
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 #21
Source File: DefaultClockImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void setCurrentTime(Date currentTime) {
    Calendar time = null;

    if (currentTime != null) {
        time = (timeZone == null) ? new GregorianCalendar() : new GregorianCalendar(timeZone);
        time.setTime(currentTime);
    }

    setCurrentCalendar(time);
}
 
Example #22
Source File: JulianDateTest.java    From solarpositioning with MIT License 5 votes vote down vote up
@Test
public void testPre02() {
    GregorianCalendar utcTime = createCalendar();
    utcTime.set(122, Calendar.JANUARY, 1, 0, 0, 0);
    utcTime.set(Calendar.ERA, GregorianCalendar.BC);
    JulianDate julDate = new JulianDate(utcTime);

    assertEquals(1676497.5, julDate.getJulianDate(), TOLERANCE);
}
 
Example #23
Source File: SalesforceConnectionTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetCalendarStartNull() throws KettleException {
  SalesforceConnection connection = new SalesforceConnection( logInterface, url, username, password );
  GregorianCalendar endDate = new GregorianCalendar( 2000, 2, 10 );
  try {
    connection.setCalendar( recordsFilter, null, endDate );
    fail();
  } catch ( KettleException expected ) {
    // OK
  }
}
 
Example #24
Source File: TimeTest.java    From caravan with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteXMLGregorianCalendarMaxDate() {
  DotNetTimeRelatedProtobuf buf = TimeRelatedConverter.xmlGregorianCalendarToNetDateTime(dataTypeFactory.newXMLGregorianCalendar(
      (GregorianCalendar) makeCalendar(9999,Calendar.DECEMBER,31,23,59,59, 999)));
  assertEquals(NetTimeSpanScale.MinMax, buf.getScale());
  assertEquals(1, buf.getValue());
}
 
Example #25
Source File: DateComponents.java    From adhan-java with MIT License 5 votes vote down vote up
/**
 * Convenience method that returns a DateComponents from a given Date
 * @param date the date
 * @return the DateComponents (according to the default device timezone)
 */
public static DateComponents from(Date date) {
  Calendar calendar = GregorianCalendar.getInstance();
  calendar.setTime(date);
  return new DateComponents(calendar.get(Calendar.YEAR),
      calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
}
 
Example #26
Source File: DateUtilsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception {
    final GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    assertEquals(year, cal.get(Calendar.YEAR));
    assertEquals(month, cal.get(Calendar.MONTH));
    assertEquals(day, cal.get(Calendar.DAY_OF_MONTH));
    assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY));
    assertEquals(min, cal.get(Calendar.MINUTE));
    assertEquals(sec, cal.get(Calendar.SECOND));
    assertEquals(mil, cal.get(Calendar.MILLISECOND));
}
 
Example #27
Source File: CalendarRegression.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void Test4073929() {
    GregorianCalendar foo1 = new GregorianCalendar(1997, 8, 27);
    foo1.add(DAY_OF_MONTH, +1);
    int testyear = foo1.get(YEAR);
    int testmonth = foo1.get(MONTH);
    int testday = foo1.get(DAY_OF_MONTH);
    if (testyear != 1997
            || testmonth != 8
            || testday != 28) {
        errln("Fail: Calendar not initialized");
    }
}
 
Example #28
Source File: StatementImpl.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Optimization to only use one calendar per-session, or calculate it for
 * each call, depending on user configuration
 */
protected Calendar getCalendarInstanceForSessionOrNew() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (this.connection != null) {
            return this.connection.getCalendarInstanceForSessionOrNew();
        }
        // punt, no connection around
        return new GregorianCalendar();
    }
}
 
Example #29
Source File: ComplexActionClass.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
@Action(name = "Complex Action Class call3")
public List<Calendar> call3() {

    List<Calendar> list = new ArrayList<Calendar>();
    list.add( new GregorianCalendar() );
    return list;
}
 
Example #30
Source File: DateUtil.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
/**
 * <pre>
 * 描述:间隔指定分钟后日期(例如:每30分钟)
 * 作者:ZhangYi
 * 时间:2016年5月5日 下午4:29:07
 * 参数:(参数列表)
 * @param dateTime	指定日期
 * @param interval	间隔分钟
 * @return
 * </pre>
 */
public static Date handleDateTimeByMinute(Date dateTime, int interval) {
	try {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(dateTime);
		calendar.add(Calendar.MINUTE, interval);
		dateTime = calendar.getTime();
	} catch (Exception e) {
		logger.error("--间隔指定分钟后日期异常!", e);
	}
	return dateTime;
}