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

The following are Jave code examples for showing how to use getTime() 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: uavstack   File: DateTimeHelper.java   View Source Code Vote up 7 votes
/**
 * @param date
 * @return 复制新Date,不改变参数
 */
public static Date nextDay(Date date) {

    Date newDate = (Date) date.clone();
    long time = (newDate.getTime() / 1000) + 60 * 60 * 24;
    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 2
Project: simple-hostel-management   File: ReservationController.java   View Source Code Vote up 7 votes
@RequestMapping(value = Mappings.RESERVATIONS_JSON_GET, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public List<Reservation> getReservations(
        @RequestParam(value = "start", required = true) String startDateStr,
        @RequestParam(value = "end", required = true) String endDateStr,
        @RequestParam(value = "accommodation", required = false, defaultValue = "-1")
                Long accommodationId) throws Exception {

    Date startDate = Utils.stringToDateTime(startDateStr, "dd/MM/YYYY HH:mm").toDate();
    Date endDate = Utils.stringToDateTime(endDateStr, "dd/MM/YYYYYY HH:mm").toDate();

    if (startDate.getTime() > endDate.getTime()) {
        throw new IllegalArgumentException("Begin date is greater than end date: " + startDateStr + " / " + endDateStr);
    }

    List<Reservation> result;
    if (accommodationId != -1) {
        result = reservationService.getByInterval(startDate, endDate, true, accommodationId);
    } else {
        result = reservationService.getByInterval(startDate, endDate, true);
    }
    return result;

}
 
Example 3
Project: Hitalk   File: DateUtils.java   View Source Code Vote up 6 votes
public static String getTimestampString(Date date) {
    String tamp = null;
    String var2 = Locale.getDefault().getLanguage();
    boolean isZh = var2.startsWith("zh");
    long time = date.getTime();
    if(isSameDay(time)) {
        if(isZh) {
            tamp = "aa hh:mm";
        } else {
            tamp = "hh:mm aa";
        }
    } else if(isYesterday(time)) {
        if(!isZh) {
            return "Yesterday " + (new SimpleDateFormat("hh:mm aa", Locale.ENGLISH)).format(date);
        }
        tamp = "昨天aa hh:mm";
    } else if(isZh) {
        tamp = "M月d日aa hh:mm";
    } else {
        tamp = "MMM dd hh:mm aa";
    }

    return isZh?(new SimpleDateFormat(tamp, Locale.CHINESE)).format(date)
            :(new SimpleDateFormat(tamp, Locale.ENGLISH)).format(date);
}
 
Example 4
Project: openNaEF   File: DtoChangesApi.java   View Source Code Vote up 6 votes
@GET
@Produces(MediaType.APPLICATION_JSON)
public static Response get(
        @QueryParam("time") Date time,
        @QueryParam("version") TransactionId.W version
) throws ApiException {
    log.debug("[handle] dto-changes");
    try {
        TransactionId.W targetTx = version != null ? version : TransactionContext.getLastCommittedTransactionId();
        Long targetTime = time != null ? time.getTime() : null;
        DtoChanges dtoChanges = DtoChangesSpawner.getDtoChanges(targetTx);
        try (AutoCloseableTx tx = AutoCloseableTx.beginTx(targetTime, targetTx)) {
            return Response.ok(Responses.json.format(DtoChangesSpawner.toMap(dtoChanges)), MediaType.APPLICATION_JSON_TYPE).build();
        }
    } catch (RemoteException e) {
        throw new InternalServerError("NAEF-00500", "NAEF通信エラー. RMI接続失敗.");
    }
}
 
Example 5
Project: jetfuel   File: Database.java   View Source Code Vote up 6 votes
/**
 * Pops a connection from the pool and checks if it is open and the last
 * used time is below 19 minutes. If those things are false, it attempts to
 * close the connection. Otherwise it returns the connection or simply
 * instantiates a new one;
 * 
 * @return
 * @throws SQLException
 */
public synchronized Connection popConnection() throws SQLException {
	if (this.transaction_connection != null)
		return this.transaction_connection;

	else if (!connection_pool.isEmpty()) {
		Connection conn = connection_pool.removeFirst();
		Date conn_used = connection_last_used.removeFirst();
		if (!conn.isClosed()) {
			// 19 minutes threshold
			if (new Date().getTime() - conn_used.getTime() <= 1140000)
				return conn;

			// just close it and do nothing
			try {
				conn.close();
			} catch (Exception e) {
			}
		} // try to pop another one;
		return popConnection();
	}

	return properties == null
			? DriverManager.getConnection(url)
			: DriverManager.getConnection(url, properties);
}
 
Example 6
Project: RxAndroidOrm   File: CatEntityManagerTest.java   View Source Code Vote up 6 votes
@Test
public void shouldGetCatWithCustomDate_after() {
    //given
    Date now = new Date(System.currentTimeMillis());

    Cat cat1 = new Cat("Java", new Date(now.getTime() - 60 * 1000 * 1000));
    Cat cat2 = new Cat("Blob", new Date(now.getTime() + 60 * 1000 * 1000));

    //when
    carEntityManager.add(cat1).subscribe();
    carEntityManager.add(cat2).subscribe();

    List<Cat> cats = carEntityManager.select().date().after(now).asObservable().blockingFirst();

    //then
    assertThat(cats).hasSize(1);
    assertThat(cats.get(0).getShortName()).isEqualTo("Blob");
}
 
Example 7
Project: dhus-core   File: ChannelFlow.java   View Source Code Vote up 6 votes
@Override
public String toString()
{
   Date current_date = new Date();

   UserQuotas user_quotas = this.getUserQuotas();
   String quotas_message =
      (user_quotas != null ? user_quotas.toString() : "User Quotas: none");

   String avg_bandwidth = "Average bandwidth: -- undetermined --";

   if (this.firstPermitDate != null)
   {
      long delay = current_date.getTime() - this.firstPermitDate.getTime();

      if (delay > 0)
      {
         avg_bandwidth =
         "Average bandwidth: "
               + (8000 * this.totalAcquiredPermits
               / ((current_date.getTime() -
                     this.firstPermitDate.getTime()) * 1048576)) + " Mbit/s";
      }
      else
      {
         avg_bandwidth = "Average bandwidth: -- transfer delay too small --";
      }
   }

   return "Channel Flow ("
         + ((this.getName() != null) ? this.getName() : "--anonymous--")
         + " x " + this.getWeight() + ") - " + quotas_message + " - "
         + avg_bandwidth;
}
 
Example 8
Project: ts-benchmark   File: CassandraDB.java   View Source Code Vote up 6 votes
@Override
	public Status selectCountByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
		long costTime = 0L;
		Cluster cluster = null;
		try {
			cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
			Session session = cluster.connect(KEY_SPACE_NAME);
			String selectCql = "SELECT COUNT(*) FROM point WHERE device_code='" + deviceCode + "' and sensor_code='"
					+ sensorCode + "' and timestamp>=" + startTime.getTime() + " and timestamp<=" + endTime.getTime()
					+ " ALLOW FILTERING";
//			System.out.println(selectCql);
			long startTime1 = System.nanoTime();
			ResultSet rs = session.execute(selectCql);
			long endTime1 = System.nanoTime();
			costTime = endTime1 - startTime1;
		} finally {
			if (cluster != null)
				cluster.close();
		}
//		System.out.println("此次查询消耗时间[" + costTime / 1000 + "]s");
		return Status.OK(costTime);
	}
 
Example 9
Project: Android_watch_magpie   File: PrologAgentMindTest.java   View Source Code Vote up 5 votes
private long convertDateToMills(String dateString) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm", Locale.getDefault());
    Date date = null;
    try {
        date = sdf.parse(dateString);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
    return date.getTime();
}
 
Example 10
Project: uavstack   File: DateTimeHelper.java   View Source Code Vote up 5 votes
public static Date getYesterday() {

        Date date = new Date();
        long time = (date.getTime() / 1000) - 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 11
Project: RLibrary   File: TimeUtil.java   View Source Code Vote up 5 votes
public static String getTimeShowRentString(long milliseconds) {
    String dataString;
    String timeStringBy24;

    Date currentTime = new Date(milliseconds);
    Date today = new Date();
    Calendar todayStart = Calendar.getInstance();
    todayStart.set(Calendar.HOUR_OF_DAY, 0);
    todayStart.set(Calendar.MINUTE, 0);
    todayStart.set(Calendar.SECOND, 0);
    todayStart.set(Calendar.MILLISECOND, 0);
    Date todaybegin = todayStart.getTime();
    Date tomorrowBegin = new Date(todaybegin.getTime() + 3600 * 24 * 1000);
    Date lastdaybegin = new Date(tomorrowBegin.getTime() + 3600 * 24 * 1000);// 后天
    Date last_daybegin = new Date(lastdaybegin.getTime() + 3600 * 24 * 1000);// 大后天


    SimpleDateFormat dateformatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
    dataString = dateformatter2.format(currentTime);

    if (currentTime.after(last_daybegin)) {
        dataString = dateformatter2.format(currentTime);
    } else if (currentTime.after(lastdaybegin)) {
        dataString += " 后天";
    } else if (currentTime.after(tomorrowBegin)) {
        dataString += " 明天";
    } else if (currentTime.after(todaybegin)) {
        dataString += " 今天";
    } else {
        dataString = dateformatter2.format(currentTime);
    }

    return dataString /*+ " " + timeStringBy24*/;

}
 
Example 12
Project: i_stolbov   File: Warehouse.java   View Source Code Vote up 5 votes
/**
 * Check the food condition for that storage.
 * @param food - Food
 * @return yes or not
 */
@Override
public boolean checkCondition(Food food) {
    Date dateNow = new Date();
    return (((double) (dateNow.getTime() - food.getCreateDate().getTime())
            / (double) (food.getExpireDate().getTime() - food.getCreateDate().getTime())) < LVL);
}
 
Example 13
Project: openjdk-jdk10   File: Renewal.java   View Source Code Vote up 5 votes
static void checkRough(Date t, int duration) throws Exception {
    Date now = new Date();
    if (t == null && duration == -1) {
        return;
    }
    long change = (t.getTime() - System.currentTimeMillis()) / 1000;
    if (change > duration + 20 || change < duration - 20) {
        throw new Exception(t + " is not " + duration);
    }
}
 
Example 14
Project: sporticus   File: Event.java   View Source Code Vote up 4 votes
@Override
public IEvent setCreated(final Date created) {
    this.created = new Date(created.getTime());
    return this;
}
 
Example 15
Project: letv   File: ap.java   View Source Code Vote up 4 votes
public final /* synthetic */ Object a(a aVar) {
    Date date = (Date) this.a.a(aVar);
    return date != null ? new Timestamp(date.getTime()) : null;
}
 
Example 16
Project: Library   File: LibraryServicesImpl.java   View Source Code Vote up 4 votes
public RestResponse addFine() {

		RestResponse response = new RestResponse();
		Session session = this.sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		try {
			String paramString = "from BookLoan where dateIn=null";
			//String paramString = "select * from book_loan where date_in is null";
			Query query = session.createQuery(paramString);

			List<BookLoan> bookLoans = query.list();

			Fine fine = null;
			Date date = new Date();
			for (BookLoan bookLoan : bookLoans) {

				if (bookLoan.getDueDate().before(date)) {

					
					if(bookLoan.getFine()==null){
						fine = new Fine(bookLoan);
					}else{
						fine = bookLoan.getFine();
					}
					
					long diff = date.getTime() - bookLoan.getDueDate().getTime();

					long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
					fine.setFineAmount(Double.toString(days * 0.25));

					session.saveOrUpdate(fine);
				}

			}
			transaction.commit();
			response.setSuccess(true);
			response.setResult("Fine updated successfully");

		} catch (Exception e) {
			transaction.rollback();
			response.setError("Error while updating. Try Again");
			response.setSuccess(false);
		}

		session.close();

		return response;
	}
 
Example 17
Project: Idea-ijkplayer   File: TimeBarView.java   View Source Code Vote up 4 votes
private void drawRecord(Canvas canvas) {
    //录像从哪个时间点开始,单位是毫秒
    long startDrawTimeInSeconds = firstTickToSeeInSecondUTC + (-20) * timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond();

    if (recordDataExistTimeClipsList != null && recordDataExistTimeClipsList.size() > 0) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String startDrawTimeDateString = dateFormat.format(startDrawTimeInSeconds * 1000);
        String zeroTimeString = startDrawTimeDateString + " 00:00:00";

        long screenLastSecondToSee = (long) (startDrawTimeInSeconds + screenWidth / pixelsPerSecond + 30 * timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond()) * 1000L;

        Date startDate;
        try {

            startDate = zeroTimeFormat.parse(zeroTimeString);
            List<RecordDataExistTimeSegment> startList = recordDataExistTimeClipsListMap.get(startDate.getTime());
            if (startList == null) {
                int afterFindDays = 1;
                long findTimeInMilliseconds = startDate.getTime();
                long newFindStartMilliseconds = findTimeInMilliseconds;
                while (startList == null && newFindStartMilliseconds < screenLastSecondToSee) {
                    newFindStartMilliseconds = findTimeInMilliseconds + (long) SECONDS_PER_DAY * 1000L * (long) afterFindDays;
                    startList = recordDataExistTimeClipsListMap.get(newFindStartMilliseconds);
                    afterFindDays++;
                }
            }

            if (startList != null && startList.size() > 0) {
                int thisDateFirstClipStartIndex = recordDataExistTimeClipsList.indexOf(startList.get(0));

                long endDrawTimeInSeconds = (long) (startDrawTimeInSeconds
                        + screenWidth / pixelsPerSecond
                        + timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond() * 30);

                timebarPaint.setColor(recordBackgroundColor);
                timebarPaint.setStyle(Paint.Style.FILL);

                for (int i = thisDateFirstClipStartIndex; i < recordDataExistTimeClipsList.size(); i++) {
                    float leftX = pixelsPerSecond * (recordDataExistTimeClipsList.get(i).getStartTimeInMillisecond() - mostLeftTimeInMillisecond) / 1000 + screenWidth / 2f;
                    float rightX = pixelsPerSecond * (recordDataExistTimeClipsList.get(i).getEndTimeInMillisecond() - mostLeftTimeInMillisecond) / 1000 + screenWidth / 2f;
                    RectF rectF = new RectF(leftX, 0, rightX, getHeight());
                    canvas.drawRect(rectF, timebarPaint);
                    if (recordDataExistTimeClipsList.get(i).getEndTimeInMillisecond() >= endDrawTimeInSeconds * 1000) {
                        break;
                    }
                }
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
 
Example 18
Project: OpenDiabetes   File: DateTimePointFilter.java   View Source Code Vote up 4 votes
public DateTimePointFilter(Date dateTimePoint, int marginInMinutes) {
    long margin = MILLISECONDS.convert(marginInMinutes, MINUTES);
    Date startTime = new Date(dateTimePoint.getTime() - margin);
    Date endTime = new Date(dateTimePoint.getTime() + margin);
    filter = new DateTimeSpanFilter(startTime, endTime);
}
 
Example 19
Project: datarouter   File: DateTool.java   View Source Code Vote up 4 votes
public static Long toReverseDateLong(Date date){
	return date == null ? null : Long.MAX_VALUE - date.getTime();
}
 
Example 20
Project: uavstack   File: DateTimeHelper.java   View Source Code Vote up 2 votes
/**
 * 将Date型时间转换成int型时间(1970年至今的秒数)
 * 
 * @param unixTime
 *            1970年至今的秒数
 * @return
 */
public static int getUnixTimeByDate(Date date) {

    return (int) (date.getTime() / 1000);
}