Java Code Examples for java.util.Date.setTime()

The following are Jave code examples for showing how to use setTime() of the java.util.Date class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: rapidminer   File: ExcelResultSet.java   View Source Code Vote up 6 votes
@Override
public Date getDate(int columnIndex) throws ParseException {
	final Cell cell = getCurrentCell(columnIndex);
	if (cell.getType() == CellType.DATE || cell.getType() == CellType.DATE_FORMULA) {
		Date date = ((DateCell) cell).getDate();

		// hack to get actual date written in excel sheet. converts date to UTC
		int offset = TimeZone.getDefault().getOffset(date.getTime());
		date.setTime(date.getTime() - offset);

		return date;
	} else {
		String valueString = cell.getContents();
		try {
			return dateFormatProvider.geDateFormat().parse(valueString);
		} catch (java.text.ParseException e) {
			throw new ParseException(
					new ParsingError(currentRow, columnIndex, ParsingError.ErrorCode.UNPARSEABLE_DATE, valueString));
		}
	}
}
 
Example 2
Project: OpenDiabetes   File: ExporterManipulator.java   View Source Code Vote up 6 votes
public static List<VaultEntry> fillBuckets2(List<VaultEntry> liste) {
    List<VaultEntry> blah = new ArrayList<>();

    long last = liste.get(liste.size() - 1).getTimestamp().getTime();
    int i = 0;
    while (liste.get(i).getTimestamp().getTime() < last) {
        Date tempDate1 = liste.get(i).getTimestamp();
        Date tempDate2 = liste.get(i + 1).getTimestamp();

        int times = Math.round(((tempDate2.getTime() - tempDate1.getTime()) / 60000));
        if (times > 0) {
            for (int j = 0; j < times - 1; j++) {
                tempDate1.setTime(tempDate1.getTime() + 60000);
                VaultEntry empty = new VaultEntry(VaultEntryType.BOLUS_SQARE, TimestampUtils.createCleanTimestamp(tempDate1));
                blah.add(empty);
                // System.out.println(empty);
            }
        }
        i = i + 1;
    }
    return blah;
}
 
Example 3
Project: jdk8u-jdk   File: KerberosTixDateTest.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    byte[] asn1Bytes = "asn1".getBytes();
    KerberosPrincipal client = new KerberosPrincipal("client");
    KerberosPrincipal server = new KerberosPrincipal("server");
    byte[] keyBytes = "sessionKey".getBytes();
    long originalTime = 12345678L;
    Date inDate = new Date(originalTime);
    boolean[] flags = new boolean[9];
    flags[8] = true; // renewable
    KerberosTicket t = new KerberosTicket(asn1Bytes, client, server,
            keyBytes, 1 /*keyType*/, flags, inDate /*authTime*/,
            inDate /*startTime*/, inDate /*endTime*/,
            inDate /*renewTill*/, null /*clientAddresses*/);
    inDate.setTime(0); // for testing the constructor

    testDateImmutability(t, originalTime);
    testS11nCompatibility(t); // S11n: Serialization
    testDestroy(t);
}
 
Example 4
Project: natumassas-app   File: Pedido.java   View Source Code Vote up 6 votes
public int getPrazo (){
    Date entrega = new Date();
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

    try{
        entrega = format.parse(this.getDataEntrega());
    }
    catch (ParseException e) {
        e.printStackTrace();
    }

    Date hoje = new Date();

    int prazo = 0;

    while (entrega.after(hoje)) {
        prazo++;
        hoje.setTime(hoje.getTime() + 86400000);
    }

    return prazo;
}
 
Example 5
Project: Biliomi   File: JWTGenerator.java   View Source Code Vote up 6 votes
private String generateToken(byte[] secretBytes, Claims claims, User user, long expiresInMillis) {
  DefaultJwsHeader jwsHeader = new DefaultJwsHeader();
  Date now = new Date();
  Date expiresAt = new Date();

  jwsHeader.setAlgorithm(signatureAlgorithm.getValue());
  jwsHeader.setType(Header.JWT_TYPE);


  expiresAt.setTime(now.getTime() + expiresInMillis);
  claims.setIssuedAt(now);
  claims.setSubject(user.getUsername());
  claims.setIssuer(Biliomi.class.getSimpleName());
  claims.setExpiration(expiresAt);
  claims.put(CLAIMS_CHANNEL, channelName);
  claims.put(CLAIMS_USER_DISPLAY_NAME, user.getDisplayName());

  JwtBuilder builder = Jwts.builder()
      .setHeader((Map<String, Object>) jwsHeader)
      .setClaims(claims)
      .signWith(signatureAlgorithm, secretBytes);

  return builder.compact();
}
 
Example 6
Project: uavstack   File: DateTimeHelper.java   View Source Code Vote up 5 votes
/**
 * 增加时间
 * 
 * @param interval
 *            [INTERVAL_DAY,INTERVAL_WEEK,INTERVAL_MONTH,INTERVAL_YEAR, INTERVAL_HOUR,INTERVAL_MINUTE]
 * @param date
 * @param n
 *            可以为负数
 * @return
 */
public static Date dateAdd(int interval, Date date, int n) {

    long time = (date.getTime() / 1000); // 单位秒
    switch (interval) {
        case INTERVAL_DAY:
            time = time + n * 86400;// 60 * 60 * 24;
            break;
        case INTERVAL_WEEK:
            time = time + n * 604800;// 60 * 60 * 24 * 7;
            break;
        case INTERVAL_MONTH:
            time = time + n * 2678400;// 60 * 60 * 24 * 31;
            break;
        case INTERVAL_YEAR:
            time = time + n * 31536000;// 60 * 60 * 24 * 365;
            break;
        case INTERVAL_HOUR:
            time = time + n * 3600;// 60 * 60 ;
            break;
        case INTERVAL_MINUTE:
            time = time + n * 60;
            break;
        case INTERVAL_SECOND:
            time = time + n;
            break;
        default:
    }

    Date result = new Date();
    result.setTime(time * 1000);
    return result;
}
 
Example 7
Project: androidtools   File: PTSqliteHelper.java   View Source Code Vote up 5 votes
public List<PTLogBean> queryLog(int priority, Date begin, Date end, int limit) {
    SQLiteDatabase db = null;
    List<PTLogBean> logList = new ArrayList<PTLogBean>();
    try {
        db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(String.format("SELECT * FROM %s WHERE %s>=? AND %s>=? AND %s<? ORDER BY %s DESC LIMIT ?", TABLE_NAME, COLUMN_LEVEL, COLUMN_DATE, COLUMN_DATE, COLUMN_DATE),
                new String[]{
                        Integer.toString(priority),
                        Long.toString(begin.getTime()),
                        Long.toString(end.getTime()),
                        Integer.toString(limit)
                }
        );

        while (cursor.moveToNext()) {
            PTLogBean logBean = new PTLogBean();
            logBean.setLevel(cursor.getInt(cursor.getColumnIndex(PTSqliteHelper.COLUMN_LEVEL)));
            logBean.setContent(cursor.getString(cursor.getColumnIndex(PTSqliteHelper.COLUMN_CONTENT)));

            String dateString = cursor.getString(cursor.getColumnIndex(PTSqliteHelper.COLUMN_DATE));
            Date date = new Date();
            date.setTime(Long.parseLong(dateString));
            logBean.setDate(date);

            logList.add(logBean);
        }
    } catch (SQLException ex) {
        return logList;
    }

    // reverse
    List<?> shallowCopy = logList.subList(0, logList.size());
    Collections.reverse(shallowCopy);
    return logList;
}
 
Example 8
Project: My-Blog   File: DateKit.java   View Source Code Vote up 5 votes
public static Date getYesterday() {
    Date date = new Date();
    long time = date.getTime() / 1000L - 86400L;
    date.setTime(time * 1000L);
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    try {
        date = format.parse(format.format(date));
    } catch (Exception var5) {
        System.out.println(var5.getMessage());
    }

    return date;
}
 
Example 9
Project: uavstack   File: DateTimeHelper.java   View Source Code Vote up 5 votes
public static Date getWeekAgo() {

        Date date = new Date();
        long time = (date.getTime() / 1000) - 7 * 60 * 60 * 24;
        date.setTime(time * 1000);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = format.parse(format.format(date));
        }
        catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return date;
    }
 
Example 10
Project: My-Blog   File: DateKit.java   View Source Code Vote up 5 votes
public static Date dateAdd(int interval, Date date, int n) {
    long time = date.getTime() / 1000L;
    switch(interval) {
        case 1:
            time += (long)(n * 86400);
            break;
        case 2:
            time += (long)(n * 604800);
            break;
        case 3:
            time += (long)(n * 2678400);
            break;
        case 4:
            time += (long)(n * 31536000);
            break;
        case 5:
            time += (long)(n * 3600);
            break;
        case 6:
            time += (long)(n * 60);
            break;
        case 7:
            time += (long)n;
    }

    Date result = new Date();
    result.setTime(time * 1000L);
    return result;
}
 
Example 11
Project: uavstack   File: DateTimeHelper.java   View Source Code Vote up 5 votes
public static Date getWeekAgo(Date date) {

        Date newDate = (Date) date.clone();
        long time = (newDate.getTime() / 1000) - 60 * 60 * 24 * 7;
        newDate.setTime(time * 1000);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            newDate = format.parse(format.format(newDate));
        }
        catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return newDate;
    }
 
Example 12
Project: Blockly   File: FieldDateTest.java   View Source Code Vote up 5 votes
@Test
public void testSetDate() {
    Date date = new Date();
    mField.setDate(date);
    assertThat(mField.getDate()).isEqualTo(date);
    date.setTime(date.getTime() + 86400000);
    mField.setTime(date.getTime());
    assertThat(mField.getDate()).isEqualTo(date);

    assertThat(mField.setFromString("2017-03-23")).isTrue();
    assertThat(mField.getLocalizedDateString()).isEqualTo("2017-03-23");
}
 
Example 13
Project: Java-9-Concurrency-Cookbook-Second-Edition   File: Task.java   View Source Code Vote up 5 votes
/**
 * Main method of the task. It generates 100 events with the same activation
 * time. The activation time will be the execution time of the thread plus
 * the id of the thread seconds
 */
@Override
public void run() {

	Date now = new Date();
	Date delay = new Date();
	delay.setTime(now.getTime() + (id * 1000));

	System.out.printf("Thread %s: %s\n", id, delay);

	for (int i = 0; i < 100; i++) {
		Event event = new Event(delay);
		queue.add(event);
	}
}
 
Example 14
Project: openjdk-jdk10   File: Duration.java   View Source Code Vote up 4 votes
/**
 * Adds this duration to a {@link Date} object.
 *
 * <p>
 * The given date is first converted into
 * a {@link java.util.GregorianCalendar}, then the duration
 * is added exactly like the {@link #addTo(Calendar)} method.
 *
 * <p>
 * The updated time instant is then converted back into a
 * {@link Date} object and used to update the given {@link Date} object.
 *
 * <p>
 * This somewhat redundant computation is necessary to unambiguously
 * determine the duration of months and years.
 *
 * @param date
 *      A date object whose value will be modified.
 * @throws NullPointerException
 *      if the date parameter is null.
 */
public void addTo(Date date) {

    // check data parameter
    if (date == null) {
        throw new NullPointerException(
            "Cannot call "
            + this.getClass().getName()
            + "#addTo(Date date) with date == null."
        );
    }

    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    this.addTo(cal);
    date.setTime(getCalendarTimeInMillis(cal));
}
 
Example 15
Project: convertigo-engine   File: TemporalInputStream.java   View Source Code Vote up 4 votes
private long findPosition(File file, Date date) throws IOException {
	RandomAccessFile raf = new RandomAccessFile(file, "r");
	
	try {
		Date cur_date = extractDate(raf);
		if (cur_date != null) {
			int compare = date.compareTo(cur_date);
			if (compare > 0) {
				date.setTime(date.getTime() - 1);
				long min = raf.getFilePointer();
				long max = raf.length();
				Date last_date = null;
				long last_pos = 0;
				while (cur_date != null && !cur_date.equals(last_date) && !cur_date.equals(date)) {
					last_date = cur_date;
					last_pos = raf.getFilePointer();
					long cur = min + ((max - min) / 2);
					raf.seek(cur);
					cur_date = extractDate(raf);
					if (cur_date == null || date.compareTo(cur_date) < 0) {
						max = cur;
					} else {
						min = cur;
					}
				}
				date.setTime(date.getTime() + 1);
				
				if (cur_date != null && date.compareTo(cur_date) < 0) {
					raf.seek(min);
					cur_date = extractDate(raf);
				}
				
				// Fix #1788 : 'Out of range Date' exception when start date is 2011-01-25 12:32 for log file of #1787
				// can find next cur_date but last_date is a valid candidate for the end date
				if (cur_date == null && last_date != null) {
					cur_date = last_date;
					raf.seek(last_pos);
				}
				while (cur_date != null && date.compareTo(cur_date) > 0) {
					raf.skipBytes(1);
					cur_date = extractDate(raf);
				}
			}
			if (cur_date != null) {
				return raf.getFilePointer();
			}
		}
		throw new IOException("Out of range Date");
	} finally {
		raf.close();
	}
}
 
Example 16
Project: OpenJSharp   File: Duration.java   View Source Code Vote up 4 votes
/**
 * Adds this duration to a {@link Date} object.
 *
 * <p>
 * The given date is first converted into
 * a {@link java.util.GregorianCalendar}, then the duration
 * is added exactly like the {@link #addTo(Calendar)} method.
 *
 * <p>
 * The updated time instant is then converted back into a
 * {@link Date} object and used to update the given {@link Date} object.
 *
 * <p>
 * This somewhat redundant computation is necessary to unambiguously
 * determine the duration of months and years.
 *
 * @param date
 *      A date object whose value will be modified.
 * @throws NullPointerException
 *      if the date parameter is null.
 */
public void addTo(Date date) {

    // check data parameter
    if (date == null) {
        throw new NullPointerException(
            "Cannot call "
            + this.getClass().getName()
            + "#addTo(Date date) with date == null."
        );
    }

    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    this.addTo(cal);
    date.setTime(getCalendarTimeInMillis(cal));
}
 
Example 17
Project: MAT-BBS_Discuz_Android   File: FormatUtils.java   View Source Code Vote up 4 votes
@SuppressLint("SimpleDateFormat")
public static Date convertDateLine (String dateLine) {
    // TODO: Finish it.
    try {
        Logger.i(TAG, "formatDate");
        return new SimpleDateFormat("yyyy-MM-dd k:m:s")
                .parse(dateLine);
    } catch (ParseException e) {
        Logger.i(TAG, "try match 7&nbsp;天前");
        // 7&nbsp;天前
        Matcher matcher = Pattern.compile("\\d+&nbsp;天前").matcher(dateLine);
        if (matcher.matches()) {
            Logger.i(TAG, "7&nbsp;天前 matches");
            if (matcher.find()) {
                Logger.i(TAG, "7&nbsp;天前 find");
                int days = Integer.parseInt(dateLine.substring(matcher.start()
                        , matcher.end()));
                return getDateBefore(new Date(), days);
            }
        } else {
            Logger.i(TAG, "try match 昨天&nbsp;23:01");
            // 昨天&nbsp;23:01
            Matcher m1 = Pattern.compile("昨天&nbsp;\\d+:\\d+").matcher(dateLine);
            if (m1.matches()) {
                Logger.i(TAG, "昨天&nbsp;23:01 matches");
                int hour = -1;
                int time = -1;
                while (m1.find()) {
                    if (hour == -1) {
                        hour = Integer.parseInt(dateLine.substring(m1.start()
                                , m1.end()));
                    } else if (time == -1) {
                        time = Integer.parseInt(dateLine.substring(m1.start()
                                , m1.end()));
                    } else break;
                }
                Logger.i(TAG, "昨天&nbsp;23:01 hour:" + hour + "time:" + time);
                Date date = new Date();
                date.setHours(hour);
                date.setTime(time);
                return getDateBefore(date, date.getDay() - 1);
            }
        }
        Logger.e(TAG, "Fail to parse date!", e);
        return new Date();
    }
}
 
Example 18
Project: puremadrid   File: GetNewData.java   View Source Code Vote up 4 votes
private void saveToDataStore(List<Medicion> mediciones) {
    mLogger.info("Storing " + mediciones.size() + " hours");

    // Saved date
    Date savedDate = Calendar.getInstance(TimeZone.getTimeZone("CET")).getTime();

    // Load datastore
    List<Entity> batch = new ArrayList<>();
    for (Medicion medicion : mediciones){
        // Measured date
        long measuredAtMillis = medicion.getMeasuredAt();
        Date measuredAt = new Date();
        Calendar measuredAtCalendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
        measuredAtCalendar.setTimeInMillis(measuredAtMillis);
        measuredAt.setTime(measuredAtMillis);
        //
        long savedAtMillis = medicion.getSavedAtHour();
        Date savedAt = new Date();
        savedAt.setTime(savedAtMillis);

        // Una entidad por cada compuesto
        for (Compuesto compuesto: Compuesto.measuredCompuestos()) {
            // Build entity
            Entity entity = new Entity(ENTITY_TYPE_MEDIDAS, measuredAt.getTime() + compuesto.getId());
            entity.setIndexedProperty(PROPERTY_COMPUESTO, compuesto.name());
            entity.setIndexedProperty(PROPERTY_AVISO, medicion.getAviso());
            entity.setIndexedProperty(PROPERTY_AVISO_STATE, medicion.getAvisoState());
            entity.setIndexedProperty(PREPERTY_AVISO_MAX_TODAY, medicion.getAvisoMaxToday());
            entity.setIndexedProperty(PROPERTY_ESCENARIO_STATE_TODAY, medicion.getEscenarioStateToday());
            entity.setIndexedProperty(PROPERTY_ESCENARIO_STATE_TOMORROW, medicion.getEscenarioStateTomorrow());
            entity.setIndexedProperty(PROPERTY_ESCENARIO_STATE_TOMORROW_MANUAL, medicion.getEscenarioManualTomorrow());
            entity.setIndexedProperty(PROPERTY_SAVED_AT, savedDate);
            entity.setIndexedProperty(PROPERTY_MEASURE_DATE, measuredAt);
            entity.setIndexedProperty(PROPERTY_MEASURE_TIME, stringHour(measuredAtCalendar.get(Calendar.HOUR_OF_DAY)));
            // Build stations
            Map<String, Object> valueMap = medicion.getCompuestoValues(compuesto);
            if (valueMap != null) {
                for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
                    entity.setUnindexedProperty(entry.getKey(), entry.getValue());
                }
            }
            // Store
            batch.add(entity);
        }
    }
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(batch);

}
 
Example 19
Project: asura   File: TriggerUtils.java   View Source Code Vote up 3 votes
/**
 * Translate a date & time from a users time zone to the another
 * (probably server) time zone to assist in creating a simple trigger with 
 * the right date & time.
 * 
 * @param date the date to translate
 * @param src the original time-zone
 * @param dest the destination time-zone
 * @return the translated date
 */
public static Date translateTime(Date date, TimeZone src, TimeZone dest) {

    Date newDate = new Date();

    int offset = (
            getOffset(date.getTime(), dest) - getOffset(date.getTime(), src));

    newDate.setTime(date.getTime() - offset);

    return newDate;
}
 
Example 20
Project: tomcat7   File: AccessLogValve.java   View Source Code Vote up 2 votes
/**
 * This method returns a ThreadLocal Date object that is set to the
 * specified time. This saves creating a new Date object for every request.
 *
 * @return Date
 */
private static Date getDate(long systime) {
    Date date = localDate.get();
    date.setTime(systime);
    return date;
}