下面列出了java.util.Calendar#getTimeInMillis ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Checks whether inbound endpoint exists till time interval specified by SERVICE_DEPLOYMENT_DELAY.
*
* @param backEndUrl backendURL
* @param sessionCookie session Cookie for the Test
* @param name name of the inbound Endpoint
* @throws Exception If an error occurs while checking for inbound
*/
public boolean isInboundEndpointDeployed(String backEndUrl, String sessionCookie, String name) throws Exception {
InboundAdminClient inboundAdmin = new InboundAdminClient(backEndUrl, sessionCookie);
InboundEndpointDTO inboundEndpointDTO = null;
log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Inbound Endpoint " + name);
Calendar startTime = Calendar.getInstance();
long time;
while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) <
SERVICE_DEPLOYMENT_DELAY) {
inboundEndpointDTO = inboundAdmin.getInboundEndpointbyName(name);
if (inboundEndpointDTO != null) {
log.info(name + "Inbound Endpoint Found in " + time + " millis");
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
//ignore
}
}
return inboundEndpointDTO != null;
}
public int getCurrentMoonPhase()
{
Calendar calendar = Calendar.getInstance();
int lp = 2551443; // full moon phase(from full to full) in seconds
calendar.setTimeInMillis(getCurrentTime()*1000);
calendar.set(Calendar.HOUR,20);
calendar.set(Calendar.MINUTE,35);
calendar.set(Calendar.SECOND,0);
long now = calendar.getTimeInMillis();
calendar.set(Calendar.YEAR,1970);
calendar.set(Calendar.MONTH,Calendar.JANUARY);
calendar.set(Calendar.DATE,7);
long new_moon = calendar.getTimeInMillis();
long phase = ((now - new_moon)/1000) % lp;
return (int)(Math.floor(phase /(24*3600)) + 1);
}
private void calculateChangeOverPoint() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.add(Calendar.DATE, 1);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
currentDateString = df.format(new Date());
// if there is an existing default log file, use the date last modified instead of the current date
if (Files.exists(defaultLogFile)) {
try {
currentDateString = df.format(new Date(Files.getLastModifiedTime(defaultLogFile).toMillis()));
} catch(IOException e){
// ignore. use the current date if exception happens.
}
}
changeOverPoint = calendar.getTimeInMillis();
}
public static java.sql.Date yesterday(){
Date date = new Date();//取时间
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
cal.add(Calendar.DATE,-1);
return new java.sql.Date(cal.getTimeInMillis());
}
public TableModel produce( final DataRow parameters, final DataFactoryContext dataFactoryContext )
throws ReportDataFactoryException {
final int limit = getTypedParameter( "limit", Integer.class, 100 );
final long seed = getTypedParameter( "seed", Long.class, System.currentTimeMillis() );
final TypedTableModel model = new TypedTableModel();
model.addColumn( "rowcount", Integer.class );
model.addColumn( "integer", Integer.class );
model.addColumn( "double", Double.class );
model.addColumn( "text", String.class );
model.addColumn( "text2", String.class );
model.addColumn( "date", Date.class );
final Random random = new Random();
random.setSeed( seed );
final Calendar baseDate = new GregorianCalendar( 2000, 1, 1 );
baseDate.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
final long millis = baseDate.getTimeInMillis();
for ( int i = 0; i < limit; i++ ) {
model.addRow( i, (int) ( random.nextDouble() * Integer.MAX_VALUE ) - ( Integer.MAX_VALUE / 2 ), random
.nextDouble()
* Integer.MAX_VALUE, "Some Text with breaks " + i, "SomeTextWithoutBreaks" + i, new Date( millis
+ (long) ( 200 * random.nextDouble() * Integer.MAX_VALUE ) ) );
}
return model;
}
private static long[] getThisYear() {
long timeNow = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new long[]{cal.getTimeInMillis(), timeNow};
}
/**
* @return milliseconds since 1.1.1970 for tomorrow 0:00:01 local timezone
*/
public static long getTomorrow() {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 1);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DATE, 1);
return c.getTimeInMillis();
}
/**
* 获取某时间所在那天几点的整点时间
* @param hour
* @return
*/
public static long getTodayByHour(long time, int hour) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
private static Date withTimeAtStartOfDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new Date(cal.getTimeInMillis());
}
public long getNextAlertTime(Context ctx) {
int time = minutes_between;
if (time < 1 || AlertPlayer.isAscendingMode(ctx)) {
time = 1;
}
Calendar calendar = Calendar.getInstance();
return calendar.getTimeInMillis() + (time * 60000);
}
@Test
public void testGetSecoendInIntraday(){
Calendar cal = Calendar.getInstance();
long now = cal.getTimeInMillis();
cal.set(Calendar.AM_PM, 0);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
int result = Dates.getSecoendInIntraday();
Assert.assertTrue(result == ((now - cal.getTimeInMillis())/1000) );
}
@Override
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
Date date = getDate(columnIndex);
if (date == null) {
wasNull = true;
return null;
} else {
wasNull = false;
cal.setTimeInMillis(date.getTime());
return new Date(cal.getTimeInMillis());
}
}
/**
* Deletes the events of the months that are too far away from the current month.
* @param currentDay The current day.
*/
private void deleteFarMonths(Calendar currentDay) {
if (mEventRects == null) return;
Calendar nextMonth = (Calendar) currentDay.clone();
nextMonth.add(Calendar.MONTH, 1);
nextMonth.set(Calendar.DAY_OF_MONTH, nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
nextMonth.set(Calendar.HOUR_OF_DAY, 12);
nextMonth.set(Calendar.MINUTE, 59);
nextMonth.set(Calendar.SECOND, 59);
Calendar prevMonth = (Calendar) currentDay.clone();
prevMonth.add(Calendar.MONTH, -1);
prevMonth.set(Calendar.DAY_OF_MONTH, 1);
prevMonth.set(Calendar.HOUR_OF_DAY, 0);
prevMonth.set(Calendar.MINUTE, 0);
prevMonth.set(Calendar.SECOND, 0);
List<EventRect> newEvents = new ArrayList<EventRect>();
for (EventRect eventRect : mEventRects) {
boolean isFarMonth = eventRect.event.getStartTime().getTimeInMillis() > nextMonth.getTimeInMillis() || eventRect.event.getEndTime().getTimeInMillis() < prevMonth.getTimeInMillis();
if (!isFarMonth) newEvents.add(eventRect);
}
mEventRects.clear();
mEventRects.addAll(newEvents);
}
final static Time fastTimeCreate(Calendar cal, int hour, int minute, int second, ExceptionInterceptor exceptionInterceptor) throws SQLException {
if (hour < 0 || hour > 24) {
throw SQLError.createSQLException(
"Illegal hour value '" + hour + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
}
if (minute < 0 || minute > 59) {
throw SQLError.createSQLException(
"Illegal minute value '" + minute + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
}
if (second < 0 || second > 59) {
throw SQLError.createSQLException(
"Illegal minute value '" + second + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
}
synchronized (cal) {
java.util.Date origCalDate = cal.getTime();
try {
cal.clear();
// Set 'date' to epoch of Jan 1, 1970
cal.set(1970, 0, 1, hour, minute, second);
long timeAsMillis = cal.getTimeInMillis();
return new Time(timeAsMillis);
} finally {
cal.setTime(origCalDate);
}
}
}
public static long getTodayTimestamp() {
Calendar date = new GregorianCalendar();
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
return date.getTimeInMillis();
}
private long expiryDate2DeltaSeconds(String dateString) {
Calendar cal = new GregorianCalendar(GMT);
for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) {
SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i],
Locale.US);
cal.set(1970, 0, 1, 0, 0, 0);
df.setTimeZone(GMT);
df.setLenient(false);
df.set2DigitYearStart(cal.getTime());
try {
cal.setTime(df.parse(dateString));
if (!COOKIE_DATE_FORMATS[i].contains("yyyy")) {
// 2-digit years following the standard set
// out it rfc 6265
int year = cal.get(Calendar.YEAR);
year %= 100;
if (year < 70) {
year += 2000;
} else {
year += 1900;
}
cal.set(Calendar.YEAR, year);
}
return (cal.getTimeInMillis() - whenCreated) / 1000;
} catch (Exception e) {
// Ignore, try the next date format
}
}
return 0;
}
public synchronized CalculatedData getMaybeCalculatedData() {
if (!ranteDataCalculating) {
ranteDataCalculating = true;
Thread thread = new Thread() {
@Override
public void run() {
super.run();
List<BgReadingStats> readings = DBSearchUtil.getReadings(false);
int day = 1000 * 60 * 60 * 24;
int timeslot = day / NO_TIMESLOTS;
Calendar date = new GregorianCalendar();
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
final long offset = date.getTimeInMillis() % day;
double[] q10 = new double[NO_TIMESLOTS];
double[] q25 = new double[NO_TIMESLOTS];
double[] q50 = new double[NO_TIMESLOTS];
double[] q75 = new double[NO_TIMESLOTS];
double[] q90 = new double[NO_TIMESLOTS];
for (int i = 0; i < NO_TIMESLOTS; i++) {
int begin = i * timeslot;
int end = begin + timeslot;
List<Double> filtered = new Vector<Double>();
for (BgReadingStats reading : readings) {
long timeOfDay = (reading.timestamp - offset) % day;
if (timeOfDay >= begin && timeOfDay < end) {
filtered.add(reading.calculated_value);
}
}
Collections.sort(filtered);
if (filtered.size() > 0) {
q10[i] = filtered.get((int) (filtered.size() * 0.1));
q25[i] = filtered.get((int) (filtered.size() * 0.25));
q50[i] = filtered.get((int) (filtered.size() * 0.50));
q75[i] = filtered.get((int) (filtered.size() * 0.75));
q90[i] = filtered.get((int) (filtered.size() * 0.9));
}
}
CalculatedData cd = new CalculatedData();
cd.q10 = q10;
cd.q25 = q25;
cd.q50 = q50;
cd.q75 = q75;
cd.q90 = q90;
setCalculatedData(cd);
}
};
thread.start();
}
//will return null if not precalculated
return calculatedData;
}
public static long getTime(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getTimeInMillis() / MILLIS_VALUE;
}
/**
* Launch the data reduction infobar promo, if it needs to be displayed.
*
* @param context An Android context.
* @param webContents The WebContents of the tab on which the infobar should show.
* @param url The URL of the page on which the infobar should show.
* @param isFragmentNavigation Whether the main frame navigation did not cause changes to the
* document (for example scrolling to a named anchor PopState).
* @param statusCode The HTTP status code of the navigation.
* @return boolean Whether the promo was launched.
*/
public static boolean maybeLaunchPromoInfoBar(Context context,
WebContents webContents, String url, boolean isErrorPage, boolean isFragmentNavigation,
int statusCode) {
ThreadUtils.assertOnUiThread();
if (webContents.isIncognito()) return false;
if (isErrorPage) return false;
if (isFragmentNavigation) return false;
if (statusCode != HttpURLConnection.HTTP_OK) return false;
if (!DataReductionPromoUtils.canShowPromos()) return false;
// Don't show the infobar promo if neither the first run experience or second run promo has
// been shown.
if (!DataReductionPromoUtils.getDisplayedFreOrSecondRunPromo()) return false;
// Don't show the promo if the user opted out on the first run experience promo.
if (DataReductionPromoUtils.getOptedOutOnFrePromo()) return false;
// Don't show the promo if the user has seen this infobar promo before.
if (DataReductionPromoUtils.getDisplayedInfoBarPromo()) return false;
// Only show the promo on HTTP pages.
if (!GURLUtils.getScheme(url).equals(UrlConstants.HTTP_SCHEME)) return false;
int currentMilestone = VersionNumberGetter.getMilestoneFromVersionNumber(
PrefServiceBridge.getInstance().getAboutVersionStrings().getApplicationVersion());
String freOrSecondRunVersion =
DataReductionPromoUtils.getDisplayedFreOrSecondRunPromoVersion();
// Temporarily allowing disk access. TODO: Fix. See http://crbug.com/577185
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
Calendar releaseDateOfM48Stable = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
releaseDateOfM48Stable.setTime(Date.valueOf(M48_STABLE_RELEASE_DATE));
long packageInstallTime = getPackageInstallTime(context);
// The boolean pref that stores whether user opted out on the first run experience was
// added in M51. If the last promo was shown before M51, then |freOrSecondRunVersion|
// will be empty. If Chrome was installed after the FRE promo was added in M48 and
// beforeM51,assume the user opted out from the FRE and don't show the infobar.
if (freOrSecondRunVersion.isEmpty()
&& packageInstallTime > releaseDateOfM48Stable.getTimeInMillis()) {
return false;
}
// Only show the promo if the current version is at least two milestones after the last
// promo was displayed or the command line switch is on. If the last promo was shown
// before M51 then |freOrSecondRunVersion| will be empty and it is safe to show the
// infobar promo.
if (!CommandLine.getInstance().hasSwitch(ENABLE_INFOBAR_SWITCH)
&& !freOrSecondRunVersion.isEmpty()
&& currentMilestone < VersionNumberGetter
.getMilestoneFromVersionNumber(freOrSecondRunVersion) + 2) {
return false;
}
DataReductionPromoInfoBar.launch(webContents,
BitmapFactory.decodeResource(context.getResources(),
R.drawable.infobar_chrome),
context.getString(R.string.data_reduction_promo_infobar_title),
context.getString(R.string.data_reduction_promo_infobar_text),
context.getString(R.string.data_reduction_promo_infobar_button),
context.getString(R.string.no_thanks));
return true;
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
/**
* Convert a calendar to a serial date value. a serial date is the number
* of days since Jan 01 1900 plus a fractional.
* @param cal the calendar object
* @return the serial date
*/
public static double toSerialDate(Calendar cal) {
long calTime = cal.getTimeInMillis();
return (((double) (calTime - SERIAL_BASE_1900) / 86400000l) + 1.0);
}