Java Code Examples for java.util.GregorianCalendar

The following examples show how to use java.util.GregorianCalendar. 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
Source Project: AsteroidOSSync   Source File: Utils_Time.java    License: 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 2
Source Project: gemfirexd-oss   Source File: SQLTime.java    License: 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 3
Source Project: astor   Source File: RelativeDateFormat.java    License: 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 4
Source Project: buffer_bci   Source File: YearTest.java    License: 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 5
Source Project: buffer_bci   Source File: MillisecondTest.java    License: 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 6
/**
 * 判断是否润年.
 * @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 7
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 8
Source Project: blessed-android   Source File: BluetoothBytesParserTest.java    License: 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 9
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 10
Source Project: TencentKona-8   Source File: Bug8074791.java    License: 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 11
Source Project: jdk8u-jdk   Source File: Bug8074791.java    License: 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 12
Source Project: astor   Source File: MonthTests.java    License: 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 13
/**
 * 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 14
Source Project: Astrosoft   Source File: Vimshottari.java    License: 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 15
Source Project: ensemble-clustering   Source File: TestTemporalDistance.java    License: 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 16
Source Project: semanticMDR   Source File: DEXService.java    License: 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 17
Source Project: tianti   Source File: DateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 月最后一天
 * @param date
 * @return
 */
public static Date getMonthEndDate(Date date){
	GregorianCalendar c = new GregorianCalendar();
	c.setTime(date);
	int maxMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
	c.set(Calendar.DAY_OF_MONTH, maxMonth);
	c.set(Calendar.HOUR_OF_DAY, 23);
	c.set(Calendar.MINUTE, 59);
	c.set(Calendar.SECOND, 59);
	return c.getTime();
}
 
Example 18
public void testFactory_FromCalendarFields() throws Exception {
    GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6);
    cal.set(Calendar.MILLISECOND, 7);
    TimeOfDay expected = new TimeOfDay(4, 5, 6, 7);
    assertEquals(expected, TimeOfDay.fromCalendarFields(cal));
    try {
        TimeOfDay.fromCalendarFields(null);
        fail();
    } catch (IllegalArgumentException ex) {}
}
 
Example 19
Source Project: nebula   Source File: DayEditor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * (non-API) Method initializeColumnHeaders. Called internally when the column
 * header text needs to be updated.
 *
 * @param columns
 *            A LinkedList of CLabels representing the column objects
 */
protected void refreshColumnHeaders(LinkedList<CLabel> columns) {
	Date startDate = getStartDate();
	GregorianCalendar gc = new GregorianCalendar();
	gc.setTime(startDate);

	SimpleDateFormat formatter = new SimpleDateFormat("EE, MMM d");
	formatter.applyLocalizedPattern(formatter.toLocalizedPattern());

	for (Iterator<CLabel> iter = columns.iterator(); iter.hasNext();) {
		CLabel headerLabel = iter.next();
		headerLabel.setText(formatter.format(gc.getTime()));
		gc.add(Calendar.DATE, 1);
	}
}
 
Example 20
private Date getRandomTime(Date minTime, Date maxTime) {
	GregorianCalendar cal = new GregorianCalendar();
	cal.setTime(minTime == null ? (new GregorianCalendar(1970, 0, 1, 0, 0, 0)).getTime() : minTime);
	cal.setTimeInMillis(cal.getTimeInMillis()
			+ nextLong(random, (maxTime == null ? (new GregorianCalendar(1970, 0, 1, 23, 59, 59)).getTime() : maxTime).getTime() - cal.getTimeInMillis()));
	return cal.getTime();
}
 
Example 21
/**
 * Before the fix, JDK8 prints: {@code
 * <record>
 *   <date>3913-11-18T17:35:40</date>
 *   <millis>1384792540403</millis>
 *   <sequence>0</sequence>
 *   <level>INFO</level>
 *   <thread>1</thread>
 *   <message>test</message>
 * </record>
 * }
 * After the fix, it should print: {@code
 * <record>
 *   <date>2013-11-18T17:35:40</date>
 *   <millis>1384792696519</millis>
 *   <sequence>0</sequence>
 *   <level>INFO</level>
 *   <thread>1</thread>
 *   <message>test</message>
 * </record>
 * }
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Locale locale = Locale.getDefault();
    try {
        Locale.setDefault(Locale.ENGLISH);

        final GregorianCalendar cal1 = new GregorianCalendar();
        final int year1 = cal1.get(Calendar.YEAR);

        LogRecord record = new LogRecord(Level.INFO, "test");
        XMLFormatter formatter = new XMLFormatter();
        final String formatted = formatter.format(record);
        System.out.println(formatted);

        final GregorianCalendar cal2 = new GregorianCalendar();
        final int year2 = cal2.get(Calendar.YEAR);
        if (year2 < 1900) {
            throw new Error("Invalid system year: " + year2);
        }

        StringBuilder buf2 = new StringBuilder()
                .append("<date>").append(year2).append("-");
        if (!formatted.contains(buf2.toString())) {
            StringBuilder buf1 = new StringBuilder()
                    .append("<date>").append(year1).append("-");
            if (formatted.contains(buf1)
                    && year2 == year1 + 1
                    && cal2.get(Calendar.MONTH) == Calendar.JANUARY
                    && cal2.get(Calendar.DAY_OF_MONTH) == 1) {
                // Oh! The year just switched in the midst of the test...
                System.out.println("Happy new year!");
            } else {
                throw new Error("Expected year " + year2
                        + " not found in log:\n" + formatted);
            }
        }
    } finally {
        Locale.setDefault(locale);
    }
}
 
Example 22
Source Project: eagle   Source File: TestDateTimeUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRound2() {
    long tsInMS = 1397016731576L;
    long tsInHour = DateTimeUtil.roundDown(Calendar.HOUR, tsInMS);
    Assert.assertEquals(1397016000000L, tsInHour);

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeInMillis(tsInMS);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Assert.assertEquals(tsInHour, cal.getTimeInMillis());
}
 
Example 23
Source Project: nebula   Source File: DateHelper.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static long daysBetween(Calendar start, Calendar end, Locale locale) {
	// create copies
	GregorianCalendar startDate = new GregorianCalendar(locale);
	GregorianCalendar endDate = new GregorianCalendar(locale);

	// switch calendars to pure Julian mode for correct day-between
	// calculation, from the Java API:
	// - To obtain a pure Julian calendar, set the change date to
	// Date(Long.MAX_VALUE).
	startDate.setGregorianChange(new Date(Long.MAX_VALUE));
	endDate.setGregorianChange(new Date(Long.MAX_VALUE));

	// set them
	startDate.setTime(start.getTime());
	endDate.setTime(end.getTime());

	// force times to be exactly the same
	startDate.set(Calendar.HOUR_OF_DAY, 12);
	endDate.set(Calendar.HOUR_OF_DAY, 12);
	startDate.set(Calendar.MINUTE, 0);
	endDate.set(Calendar.MINUTE, 0);
	startDate.set(Calendar.SECOND, 0);
	endDate.set(Calendar.SECOND, 0);
	startDate.set(Calendar.MILLISECOND, 0);
	endDate.set(Calendar.MILLISECOND, 0);

	// now we should be able to do a "safe" millisecond/day caluclation to
	// get the number of days
	long endMilli = endDate.getTimeInMillis();
	long startMilli = startDate.getTimeInMillis();

	// calculate # of days, finally
	long diff = (endMilli - startMilli) / MILLISECONDS_IN_DAY;

	return diff;
}
 
Example 24
Source Project: diirt   Source File: TimeScalesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void createReferencesEmpty1() {
//test time period too big
GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 );
cal.set( GregorianCalendar.MILLISECOND , 1 );
Instant start = cal.getTime().toInstant();
TimeInterval timeInterval = TimeInterval.between( start , start.plus( Duration.ofMillis( -5 ) ) );
List<Instant> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 1 ) );
assertThat( references.size() , equalTo(0) );
}
 
Example 25
Source Project: jtransc   Source File: ZipEntry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the last modification time of this {@code 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 26
GetPrescriptionForExecutorResultSealed(String rid, Date creationDate, String patientId, boolean feedbackAllowed, boolean feedbackAllowedByPatient, byte[] prescription, String encryptionKeyId, String prescriptionType, String timestampingId, String prescriberId) {
   this.rid = rid;
   this.creationDate = new GregorianCalendar();
   this.creationDate.setTime(creationDate);
   this.patientId = Utils.formatId(patientId, 11);
   this.feedbackAllowed = feedbackAllowed && feedbackAllowedByPatient;
   this.prescription = prescription;
   this.encryptionKeyId = encryptionKeyId;
   this.prescriptionType = prescriptionType;
   this.timestampingId = timestampingId;
   this.prescriberId = prescriberId;
}
 
Example 27
Source Project: blog-codes   Source File: mxPngImageEncoder.java    License: Apache License 2.0 5 votes vote down vote up
private void writeTIME() throws IOException
{
	if (param.isModificationTimeSet())
	{
		ChunkStream cs = new ChunkStream("tIME");

		Date date = param.getModificationTime();
		TimeZone gmt = TimeZone.getTimeZone("GMT");

		GregorianCalendar cal = new GregorianCalendar(gmt);
		cal.setTime(date);

		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int minute = cal.get(Calendar.MINUTE);
		int second = cal.get(Calendar.SECOND);

		cs.writeShort(year);
		cs.writeByte(month + 1);
		cs.writeByte(day);
		cs.writeByte(hour);
		cs.writeByte(minute);
		cs.writeByte(second);

		cs.writeToStream(dataOutput);
		cs.close();
	}
}
 
Example 28
Source Project: java-binance-api   Source File: MarketDataEndpointsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testKlinesEndpointWithOptions() throws Exception, BinanceApiException {
    // picking interval of last 3 days
    Long timeEnd = new Date().getTime();
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(new Date());
    cal.add(Calendar.DATE, -3);
    Long timeStart = cal.getTime().getTime();

    Map<String, Long> options = ImmutableMap.of("startTime", timeStart, "endTime", timeEnd);
    List<BinanceCandlestick> klines = binanceApi.klines(symbol, BinanceInterval.FIFTEEN_MIN, 50, options);
    assertTrue("Klines should return non-empty array of candlesticks", klines.size() > 0);

    BinanceCandlestick firstCandlestick = klines.get(0);
    log.info(firstCandlestick.toString());
    assertNotNull("Candlestick should contain open", firstCandlestick.getOpen());
    assertNotNull("Candlestick should contain high", firstCandlestick.getHigh());
    assertNotNull("Candlestick should contain low", firstCandlestick.getLow());
    assertNotNull("Candlestick should contain close", firstCandlestick.getClose());
    assertNotNull("Candlestick should contain openTime", firstCandlestick.getOpenTime());
    assertNotNull("Candlestick should contain closeTime", firstCandlestick.getCloseTime());
    assertNotNull("Candlestick should contain numberOfTrades", firstCandlestick.getNumberOfTrades());
    assertNotNull("Candlestick should contain volume", firstCandlestick.getVolume());
    assertNotNull("Candlestick should contain quoteAssetVolume", firstCandlestick.getQuoteAssetVolume());
    assertNotNull("Candlestick should contain takerBuyBaseAssetVolume", firstCandlestick.getTakerBuyBaseAssetVolume());
    assertNotNull("Candlestick should contain takerBuyQuoteAssetVolume", firstCandlestick.getTakerBuyQuoteAssetVolume());
}
 
Example 29
Source Project: ambry   Source File: GetPeersHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If {@code exception} is null, gathers all the peers of the datanode that corresponds to the params in the request
 * and returns them as a JSON with the field {@link #PEERS_FIELD_NAME} whose value is a JSON array of objects with
 * fields {@link #NAME_QUERY_PARAM} and {@link #PORT_QUERY_PARAM}.
 * @param result The result of the request. This would be non null when the request executed successfully
 * @param exception The exception that was reported on execution of the request
 */
@Override
public void onCompletion(Void result, Exception exception) {
  long processingStartTimeMs = SystemTime.getInstance().milliseconds();
  metrics.getPeersSecurityPostProcessRequestTimeInMs.update(processingStartTimeMs - operationStartTimeMs);
  ReadableStreamChannel channel = null;
  try {
    if (exception == null) {
      DataNodeId dataNodeId = getDataNodeId(restRequest);
      LOGGER.trace("Getting peer hosts for {}:{}", dataNodeId.getHostname(), dataNodeId.getPort());
      Set<DataNodeId> peerDataNodeIds = new HashSet<>();
      List<? extends ReplicaId> replicaIdList = clusterMap.getReplicaIds(dataNodeId);
      for (ReplicaId replicaId : replicaIdList) {
        List<? extends ReplicaId> peerReplicaIds = replicaId.getPeerReplicaIds();
        for (ReplicaId peerReplicaId : peerReplicaIds) {
          peerDataNodeIds.add(peerReplicaId.getDataNodeId());
        }
      }
      channel = getResponseBody(peerDataNodeIds);
      restResponseChannel.setHeader(RestUtils.Headers.DATE, new GregorianCalendar().getTime());
      restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, RestUtils.JSON_CONTENT_TYPE);
      restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH, channel.getSize());
    }
  } catch (Exception e) {
    exception = e;
  } finally {
    metrics.getPeersProcessingTimeInMs.update(SystemTime.getInstance().milliseconds() - processingStartTimeMs);
    callback.onCompletion(exception == null ? channel : null, exception);
  }
}
 
Example 30
Source Project: diirt   Source File: TimeScalesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void createReferencesLowerBoundary4() {
GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 );
cal.set( GregorianCalendar.MILLISECOND , 999 );
Instant start = cal.getTime().toInstant();
TimeInterval timeInterval = TimeInterval.between( start , start.plus( Duration.ofMillis( 3 ) ) );
List<Instant> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 3 ) );
assertThat( references.size() , equalTo(2) );
assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 999 ) ) );
assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 2 ) ) );
}