I would like to write one line of code to calculate the number of milliseconds in 30 days.
long gracePeriod = 30/*days*/ * 24 * 60 * 60 * 1000;
However, in the drool that will not work because it is assigning an int to a long. So I figured I could do something like this.
long gracePeriod = 30l/*days*/ * 24l * 60l * 60l * 1000l;
But, that also will not work so I had to do something dumb like:
long grace1 = 30;
long grace2 = 24;
long grace3 = 60;
long grace4 = 1000;
long grace = grace1 * grace2 * grace3 * grace3 * grace4;
Is there any way to make this simpler.
For me, all 4 of these samples work (and are cleaner than what you had to resort to). If one or many isn't working for you, it's probably either a problem with your IDE or Java environment. If so, let us know what java version you're running and the environment.
public class TempProject
{
public static void main(String args[])
{
long gracePeriod = 30l /*days*/ * 24l * 60l * 60l * 1000l;
long gracePeriod2 = 30l /*days*/ * 24 * 60 * 60 * 1000;
long gracePeriod3 = ((long)30) /*days*/ * 24 * 60 * 60 * 1000;
long gracePeriod4 = ((long) 30)/*days*/ * ((long) 24) * ((long) 60) * ((long) 60) * ((long) 1000);
System.out.println(gracePeriod);
System.out.println(gracePeriod2);
System.out.println(gracePeriod3);
System.out.println(gracePeriod4);
}
}
Of course the easiest way is to hardcode the number ;)
long gracePeriod = 2592000000l;
Related
This is my code, but its output does make any sense.
long currentTime;
long stateStartTime;
int delta;
float speed;
// I do something
System.out.println();
System.out.println(currentTime);
System.out.println(stateStartTime);
System.out.println(delta);
System.out.println(speed);
System.out.println(delta * speed);
System.out.println(currentTime - (stateStartTime + (delta * speed)));
stateStartTime += delta * speed;
System.out.println(currentTime - stateStartTime);
Output:
1350065634345877
1350065121656832
1
5.0E8
5.0E8
0.0
-24181867
I was expecting the last two rows to be:
12689045
12689045
But surprisingly I got the above result. Why?
Don't drop precision and expect the computer to re-create it.
long currentTime = 1350065634345877L;
long stateStartTime = 1350065121656832L;
long delta = 1L;
double speed = 5.0E8;
And your last two lines (with no other changes) output
1.2689045E7
12689045
To make the penultimate line match the final line, you could use a BigDecimal like
System.out.println(new BigDecimal(currentTime - (stateStartTime + (delta * speed)))
.toPlainString());
How can I convert 0.230324074074074 to 05:31:40 in Java? I have code in sql but need in java.
(select * from(SELECT TRUNC (
( (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
* 24
* 60)
/ 60)
|| ':'
|| ( ( (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
* 24
* 60)
- TRUNC (
( ( X_GSA_LEAVE_SITE
- X_GSA_ARRIVE_ONSITE)
* 24
* 60)
/ 60)
* 60)
It appears that the value 0.230324 is a fraction of a day, and you want to display this as hours:minutes:seconds. There is a fairly straightforward way to do this in Java 8:
double input = 0.230324074074074d;
long seconds = new Double(input*24*60*60).longValue();
System.out.println(LocalTime.MIN.plusSeconds(seconds)
.format(DateTimeFormatter.ISO_LOCAL_TIME));
05:31:39
Demo
You can convert that fraction of day to a LocalTime using:
LocalTime.ofSecondOfDay((long)(0.230324074074074 * 24 * 60 * 60))
This converts the value to seconds and constructs a LocalTime object. Printing the result outputs "05:31:39" (LocalTime.toString outputs time in your desired format). You may need to control rounding in a different way if you expect exactly 05:31:40)
Just for fun here is an old fashioned Calendar version
int seconds = (int) (0.230324074074074 * 24 * 60 * 60);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.SECOND, seconds);
String result = String.format("%02d:%02d:%02d",
cal.get(Calendar.HOUR),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND));
System.out.println(result);
long seconds = (long) (0.230324074074074 * 24 * 60 * 60);
String result = String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
System.out.println(result);
I am making an app which can show time left to some date, and an elapsed time after some date. But I endure some difficulties with dates less than 1970 and bigger than 3300. I have found an explanation why it happens.
The problem is this sentence from getTimeInMillis:
the current time as UTC milliseconds from the epoch.
And, as far as i remember, the epoch started on January 1st 1970 you get a negative number for anything before that.
My question is how to solve this problem. (And yes i have heard about JodaTime, I am not allowed to use this library in this app.)
What default(standard) tools should i use?
Here it is a piece of code that does not work properly.
private void getDateTime()
{
Date date = new Date();
timeRemaining = Calendar.getInstance();
date.setTime(timeRemaining.getTimeInMillis());
millis = Math.abs(timeRemaining.getTimeInMillis() - targetDate.getTimeInMillis());
int scnds = (int) (millis / 1000) % 60 ;
int mnts = (int) ((millis / (1000 * 60)) % 60);
int hrs = (int) ((millis / (1000 * 60 * 60)) % 24);
int dys = (int) (millis / (1000 * 60 * 60 * 24));
resultDate.setText(getString(R.string.formating, dys, hrs, mnts, scnds));
}
You can achieve this by leveraging the Duration and LocalDateTime class(es) introduced in Java 8 --
import java.time.Duration;
import java.time.LocalDateTime;
class Main {
public static void main(String[] args) {
LocalDateTime fromDateTime = LocalDateTime.of(1914, 9, 10, 0, 0, 0);
LocalDateTime toDateTime = LocalDateTime.of(2014, 12, 16, 0, 0, 0);
System.out.println(Duration.between(fromDateTime, toDateTime).toMillis());
}
}
I am busy with transmitting a Bluetooth Low Energy UUID via my Raspberry Pi. That setup is done and works to a satisfactory extent.
But now my personal objective is to make a very simple android app, that catches this UUID and displays it on the android screen.
So after some browsing around, I found this Radius Network iBeacon package with a iBeacon.java code in it.
I am very new to Android Studio. For the life of me, I can't seem to debug that iBeacon.java code to my android (Jellybean) phone..
So basically the directory for that code looks like this:
android-ibeacon-service/src/com/radiusnetworks/ibeacon/client/iBeacon.java
I guess the first directory part is the package?
I have tried importing the whole thing, but it shows so many things not working,
I have also tried just importing the iBeacon.java code.. But that doesn't run to my phone..
The iBeacon.java looks like this:
/**
* Radius Networks, Inc.
* http://www.radiusnetworks.com
*
* #author David G. Young
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.radiusnetworks.ibeacon;
import java.util.Collections;
import com.radiusnetworks.ibeacon.client.RangedIBeacon;
import android.util.Log;
/**
* The <code>IBeacon</code> class represents a single hardware iBeacon detected by
* an Android device.
*
* <pre>An iBeacon is identified by a three part identifier based on the fields
* proximityUUID - a string UUID typically identifying the owner of a
* number of ibeacons
* major - a 16 bit integer indicating a group of iBeacons
* minor - a 16 bit integer identifying a single iBeacon</pre>
*
* An iBeacon sends a Bluetooth Low Energy (BLE) advertisement that contains these
* three identifiers, along with the calibrated tx power (in RSSI) of the
* iBeacon's Bluetooth transmitter.
*
* This class may only be instantiated from a BLE packet, and an RSSI measurement for
* the packet. The class parses out the three part identifier, along with the calibrated
* tx power. It then uses the measured RSSI and calibrated tx power to do a rough
* distance measurement (the accuracy field) and group it into a more reliable buckets of
* distance (the proximity field.)
*
* #author David G. Young
* #see Region#matchesIBeacon(IBeacon iBeacon)
*/
public class IBeacon {
/**
* Less than half a meter away
*/
public static final int PROXIMITY_IMMEDIATE = 1;
/**
* More than half a meter away, but less than four meters away
*/
public static final int PROXIMITY_NEAR = 2;
/**
* More than four meters away
*/
public static final int PROXIMITY_FAR = 3;
/**
* No distance estimate was possible due to a bad RSSI value or measured TX power
*/
public static final int PROXIMITY_UNKNOWN = 0;
final private static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private static final String TAG = "IBeacon";
/**
* A 16 byte UUID that typically represents the company owning a number of iBeacons
* Example: E2C56DB5-DFFB-48D2-B060-D0F5A71096E0
*/
protected String proximityUuid;
/**
* A 16 bit integer typically used to represent a group of iBeacons
*/
protected int major;
/**
* A 16 bit integer that identifies a specific iBeacon within a group
*/
protected int minor;
/**
* An integer with four possible values representing a general idea of how far the iBeacon is away
* #see #PROXIMITY_IMMEDIATE
* #see #PROXIMITY_NEAR
* #see #PROXIMITY_FAR
* #see #PROXIMITY_UNKNOWN
*/
protected Integer proximity;
/**
* A double that is an estimate of how far the iBeacon is away in meters. This name is confusing, but is copied from
* the iOS7 SDK terminology. Note that this number fluctuates quite a bit with RSSI, so despite the name, it is not
* super accurate. It is recommended to instead use the proximity field, or your own bucketization of this value.
*/
protected Double accuracy;
/**
* The measured signal strength of the Bluetooth packet that led do this iBeacon detection.
*/
protected int rssi;
/**
* The calibrated measured Tx power of the iBeacon in RSSI
* This value is baked into an iBeacon when it is manufactured, and
* it is transmitted with each packet to aid in the distance estimate
*/
protected int txPower;
/**
* If multiple RSSI samples were available, this is the running average
*/
protected Double runningAverageRssi = null;
/**
* #see #accuracy
* #return accuracy
*/
public double getAccuracy() {
if (accuracy == null) {
accuracy = calculateAccuracy(txPower, runningAverageRssi != null ? runningAverageRssi : rssi );
}
return accuracy;
}
/**
* #see #major
* #return major
*/
public int getMajor() {
return major;
}
/**
* #see #minor
* #return minor
*/
public int getMinor() {
return minor;
}
/**
* #see #proximity
* #return proximity
*/
public int getProximity() {
if (proximity == null) {
proximity = calculateProximity(getAccuracy());
}
return proximity;
}
/**
* #see #rssi
* #return rssi
*/
public int getRssi() {
return rssi;
}
/**
* #see #txPower
* #return txPowwer
*/
public int getTxPower() {
return txPower;
}
/**
* #see #proximityUuid
* #return proximityUuid
*/
public String getProximityUuid() {
return proximityUuid;
}
#Override
public int hashCode() {
return minor;
}
/**
* Two detected iBeacons are considered equal if they share the same three identifiers, regardless of their distance or RSSI.
*/
#Override
public boolean equals(Object that) {
if (!(that instanceof IBeacon)) {
return false;
}
IBeacon thatIBeacon = (IBeacon) that;
return (thatIBeacon.getMajor() == this.getMajor() && thatIBeacon.getMinor() == this.getMinor() && thatIBeacon.getProximityUuid() == thatIBeacon.getProximityUuid());
}
/**
* Construct an iBeacon from a Bluetooth LE packet collected by Android's Bluetooth APIs
*
* #param scanData The actual packet bytes
* #param rssi The measured signal strength of the packet
* #return An instance of an <code>IBeacon</code>
*/
public static IBeacon fromScanData(byte[] scanData, int rssi) {
if (((int)scanData[5] & 0xff) == 0x4c &&
((int)scanData[6] & 0xff) == 0x00 &&
((int)scanData[7] & 0xff) == 0x02 &&
((int)scanData[8] & 0xff) == 0x15) {
// yes! This is an iBeacon
}
else if (((int)scanData[5] & 0xff) == 0x2d &&
((int)scanData[6] & 0xff) == 0x24 &&
((int)scanData[7] & 0xff) == 0xbf &&
((int)scanData[8] & 0xff) == 0x16) {
// this is an Estimote beacon
IBeacon iBeacon = new IBeacon();
iBeacon.major = 0;
iBeacon.minor = 0;
iBeacon.proximityUuid = "00000000-0000-0000-0000-000000000000";
iBeacon.txPower = -55;
return iBeacon;
}
else {
// This is not an iBeacon
Log.d(TAG, "This is not an iBeacon advertisment. The bytes I see are: "+bytesToHex(scanData));
return null;
}
IBeacon iBeacon = new IBeacon();
iBeacon.major = (scanData[25] & 0xff) * 0x100 + (scanData[26] & 0xff);
iBeacon.minor = (scanData[27] & 0xff) * 0x100 + (scanData[28] & 0xff);
iBeacon.txPower = (int)scanData[29]; // this one is signed
iBeacon.rssi = rssi;
// AirLocate:
// 02 01 1a 1a ff 4c 00 02 15 # Apple's fixed iBeacon advertising prefix
// e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon profile uuid
// 00 00 # major
// 00 00 # minor
// c5 # The 2's complement of the calibrated Tx Power
// Estimote:
// 02 01 1a 11 07 2d 24 bf 16
// 394b31ba3f486415ab376e5c0f09457374696d6f7465426561636f6e00000000000000000000000000000000000000000000000000
byte[] proximityUuidBytes = new byte[16];
System.arraycopy(scanData, 9, proximityUuidBytes, 0, 16);
String hexString = bytesToHex(proximityUuidBytes);
StringBuilder sb = new StringBuilder();
sb.append(hexString.substring(0,8));
sb.append("-");
sb.append(hexString.substring(8,12));
sb.append("-");
sb.append(hexString.substring(12,16));
sb.append("-");
sb.append(hexString.substring(16,20));
sb.append("-");
sb.append(hexString.substring(20,32));
iBeacon.proximityUuid = sb.toString();
return iBeacon;
}
protected IBeacon(IBeacon otherIBeacon) {
this.major = otherIBeacon.major;
this.minor = otherIBeacon.minor;
this.accuracy = otherIBeacon.accuracy;
this.proximity = otherIBeacon.proximity;
this.rssi = otherIBeacon.rssi;
this.proximityUuid = otherIBeacon.proximityUuid;
this.txPower = otherIBeacon.txPower;
}
protected IBeacon() {
}
protected static double calculateAccuracy(int txPower, double rssi) {
if (rssi == 0) {
return -1.0; // if we cannot determine accuracy, return -1.
}
Log.d(TAG, "calculating accuracy based on rssi of "+rssi);
double ratio = rssi*1.0/txPower;
if (ratio < 1.0) {
return Math.pow(ratio,10);
}
else {
double accuracy = (0.89976)*Math.pow(ratio,7.7095) + 0.111;
Log.d(TAG, " avg rssi: "+rssi+" accuracy: "+accuracy);
return accuracy;
}
}
protected static int calculateProximity(double accuracy) {
if (accuracy < 0) {
return PROXIMITY_UNKNOWN;
// is this correct? does proximity only show unknown when accuracy is negative? I have seen cases where it returns unknown when
// accuracy is -1;
}
if (accuracy < 0.5 ) {
return IBeacon.PROXIMITY_IMMEDIATE;
}
// forums say 3.0 is the near/far threshold, but it looks to be based on experience that this is 4.0
if (accuracy <= 4.0) {
return IBeacon.PROXIMITY_NEAR;
}
// if it is > 4.0 meters, call it far
return IBeacon.PROXIMITY_FAR;
}
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
How can I solve this mystery? :)
I'm the one who wrote that IBeacon.java code about two years ago. Since then it has been rewritten and is now available in a ready to run Android Studio reference app here:
https://github.com/AltBeacon/android-beacon-library-reference
You do have to make one change to it to get it to detect iBeacons. See here for that change:
Is this the correct layout to detect iBeacons with AltBeacon's Android Beacon Library?
I have a count down timer that works fine except for I'm geting numbers that have more then 2 digits for the 100th of seconds. I'm creating 2 calendar objects, bgetting there time alue in milli secons, and subtracting it. code
long milsecs1= calendar1.getTimeInMillis();
long milsecs2 = calendar2.getTimeInMillis();
long diff = milsecs2 - milsecs1;
long dsecs = diff / 1000;
long ddays = diff / (24 * 60 * 60 * 1000);
diff=diff-ddays *(24 * 60 * 60 * 1000);
textDays.setText( Integer.toString( (int)ddays)+":" );
long dhours = diff / (60 * 60 * 1000);
diff=diff-dhours* (60 * 60 * 1000);
textHours.setText( Integer.toString( (int)dhours)+":" );
long dminutes = diff / (60 * 1000);
diff=diff-dminutes* (60 * 1000);
textMinuts.setText( Integer.toString( (int)dminutes)+":" );
/////////////////////////////////////////////////
// THIS IS THE PART THAT IS NOT WORKING, I WANT NUMBERS 0-99, BUT GETTING NUMBERS LIKE 230
long dseconds = diff / (100);
textSeconds.setText( Integer.toString( (int)dseconds)+":" );
diff=diff-dseconds;
Joda time provides a much simpler (and thoroughly proven) solution in its Period class. Something like this should do the trick (untested):
Period period = new Period(calendar1.getTimeInMillis(), calendar2.getTimeInMillis());
int days = period.getDays();
int hours = period.getHours();
... etc.