I got the time from the launcher and time from system...I want to compare them and make sure that the difference is not more than 100milliseconds
public void test() throws InterruptedException {
/*
* Get the visible time from the launcher
*/
TextView onLauncherDisplay = (TextView) mNextUIMainActivity.findViewById(R.id.timeOfDay);
System.out.println("Launcher time: " + onLauncherDisplay.getText().toString());
/*
* Get the system time
*/
Calendar currentSystemTime = Calendar.getInstance();
currentSystemTime.setTime(new Date());
Calendar currentSystemTImeInMIlliseconds = Calendar.getInstance();
currentSystemTImeInMIlliseconds.seu
/*
* Convert time into 12-hour format
*/
SimpleDateFormat date = new SimpleDateFormat("h:mm aa");
Calendar onLauncherTime = Calendar.getInstance();
try {
onLauncherTime.setTime(date.parse(onLauncherDisplay.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("System time: " + currentSystemTime.get(Calendar.HOUR) + ":" + currentSystemTime.get(Calendar.MINUTE));
Here i am comparing the time...hours and minutes but it is not perfect. I want to convert into milliseconds and the difference should not be more than 100 milliseconds
/*
* Compare the Launcher time with the System time
*/
if ((onLauncherTime.get(Calendar.HOUR) == currentSystemTime.get(Calendar.HOUR)) || (currentSystemTime.get(Calendar.HOUR) - onLauncherTime.get(Calendar.HOUR) == 1)) {
if (onLauncherTime.get(Calendar.MINUTE) == currentSystemTime.get(Calendar.MINUTE) || (currentSystemTime.get(Calendar.MINUTE) - onLauncherTime.get(Calendar.MINUTE) == 1)) {
System.out.println("Launcher time matches the On-System time!");
}
} else {
System.out.println("Launcher time does not matches the On-System time!!");
}
Use Calendar.getTimeInMillis():
if (currentSystemTime.getTimeInMillis() - onLauncherTime.getTimeInMillis() < 100)
//difference is less than 100 milliseconds
The Calendar class has a method getTimeInMillis that returns the unix epoc time value for the given calendar. That said, I don't fully understand what you're doing...
Related
I have a Date object that I want to convert it back to a Timestamp, the logic behind that is the user can input a event date and then that input gets converted to it's corresponding Timestamp and then uploaded to Firebase Firestore.
I have to use this method to make the sorting easier and accurate, between a list of dates, the nearest one gets displayed to user.
I have the other way around (convert a Timestamp into a date) up and running
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();
How to reverse this algorithm to meet my requirements ?
According the documentation of java.util.Calendar.getTimeInMillis() it will return the current time as UTC milliseconds from epoch.
According that, you could do something as
public long dateToTimestamp(Date date) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTime(date);
return cal.getTimeInMillis() / 1000L;
}
I've tested and it works perfectly.
class Main {
public static long dateToTimestamp(Date date) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTime(date);
return cal.getTimeInMillis() / 1000L;
}
public static Date timeStampToDate(long timestamp) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp * 1000L);
return cal.getTime();
}
public static void main(String[] args) {
long date = 1000;
System.out.println("Time as Date: " + timeStampToDate(date));
System.out.println("Time in timestamp: " + dateToTimestamp(timeStampToDate(date)));
}
}
One test case that tests that the method really does the opposite than the one that you've in the question:
#Test
void testTimestampConversion() {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
// Present
long expected = dateToTimestamp(cal.getTime());
assertEquals(expected, dateToTimestamp(timeStampToDate(expected)));
// Past
long expectedPast = 1000;
assertEquals(expectedPast, dateToTimestamp(timeStampToDate(expectedPast)));
// Future
Date future = cal.getTime();
future.setYear(3000);
long expectedFuture = dateToTimestamp(future);
assertEquals(expectedFuture, dateToTimestamp(timeStampToDate(expectedFuture)));
}
I want some Java code that will tell me when school is open based on the current time.
When I call this method between 9AM and 6PM it should return "school is open", otherwise it should return "school is closed" after 6 pm and before 9 am.
public Calendar shopStartTime(String msg)
{
Calendar currentTime = Calendar.getInstance();
Calendar schoolTime = Calendar.getInstance();
Calendar schoolClosedTime = Calendar.getInstance();
schoolTime.set(Calendar.HOUR_OF_DAY, 9);
schoolTime.set(Calendar.MINUTE, 0);
schoolTime.set(Calendar.SECOND, 0);
schoolTime.set(Calendar.MILLISECOND, 0);
schoolClosedTime.set(Calendar.HOUR_OF_DAY, 18);
schoolClosedTime.set(Calendar.MINUTE, 0);
schoolClosedTime.set(Calendar.SECOND, 0);
schoolClosedTime.set(Calendar.MILLISECOND, 0);
if (schoolTime.compareTo(currentTime) <= 0 &&
(currentTime.compareTo(schoolClosedTime)>=0))
{
// check for time
Toast.makeText(getSherlockActivity(), "school is closed ",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getSherlockActivity(), " school is open",
Toast.LENGTH_SHORT).show();
}
return currentTime;
}
But the code is not working because it always returns the same result. How do I test if one time is between two other time of days?
Read the javadocs!
if (currentTime.after(schoolTime) && currentTime.before(schoolClosedTime)) {
// school is open
} else {
// school is closed
}
check if hour <9 && hour >18:
(or something else)
Calendar currentTime = Calendar.getInstance();
int hour = currentTime.get(Calendar.HOUR_OF_DAY);
you only need ONE calendar
Apart from Calendar that you have used , another simple approach would be :
private boolean inRange(Date now) throws ParseException {
final Date start = new SimpleDateFormat("HH.mm.ss").parse("09.00.00");
final Date end = new SimpleDateFormat("HH.mm.ss").parse("18.00.00");
return now.after(start)&& now.before(end);
}
You can use before() and after() of Calendar as well .
I have a datetime in a variable previous. Now i want to check if the previous datetime is more than twenty minutes before the current time.
Date previous = myobj.getPreviousDate();
Date now = new Date();
//check if previous was before 20 minutes from now ie now-previous >=20
How can we do it?
Use
if (now.getTime() - previous.getTime() >= 20*60*1000) {
...
}
Or, more verbose, but perhaps slightly easier to read:
import static java.util.concurrent.TimeUnit.*;
...
long MAX_DURATION = MILLISECONDS.convert(20, MINUTES);
long duration = now.getTime() - previous.getTime();
if (duration >= MAX_DURATION) {
...
}
Using Joda Time:
boolean result = Minutes.minutesBetween(new DateTime(previous), new DateTime())
.isGreaterThan(Minutes.minutes(20));
Java 8 solution:
private static boolean isAtleastTwentyMinutesAgo(Date date) {
Instant instant = Instant.ofEpochMilli(date.getTime());
Instant twentyMinutesAgo = Instant.now().minus(Duration.ofMinutes(20));
try {
return instant.isBefore(twentyMinutesAgo);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
You should really use Calendar object instead of Date:
Calendar previous = Calendar.getInstance();
previous.setTime(myobj.getPreviousDate());
Calendar now = Calendar.getInstance();
long diff = now.getTimeInMillis() - previous.getTimeInMillis();
if(diff >= 20 * 60 * 1000)
{
//at least 20 minutes difference
}
Get the times in milliseconds, and check the difference:
long diff = now.getTime() - previous.getTime();
if (diff > 20L * 60 * 1000) {
// ...
}
Another solution could be to use Joda time.
I have a Timestamp being passed from an external source to my application in the 2011-01-23-12.31.45 format. I need to compare it to the current system timestamp an make sure its less than 2 minutes difference. Any ideas on how to accomplish this?
That's a date, not a timestamp. You can parse it using java.text.SimpleDateFormat, using the yyyy-dd-MM-HH.mm.ss format:
SimpleDateFormat sdf = new SimpleDateFormat("yyy-dd-MM-HH.mm.ss");
Date date = sdf.parse(inputDateString);
long timestamp = date.getTime();
And then compare - a minute has 60 * 1000 millis.
Using joda-time for date-time operations is always preferred - it will:
have a thread-safe implementation of the dataformat - DateTimeFormat (the one above is not thread-safe)
simply do Minutes.minutesBetween(..) to find out the minutes between the two instants, rather than calculating.
Well this can be optimized but this is what I came up with. It needs some work but it should get you started.
public class Test {
private final String serverValue = "2011-01-23-12.31.45"; //Old should fail
private final String serverValueNew = "2011-03-28-14.02.00"; //New
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss");
public boolean plusMinusTwoMins(String serverValue) {
boolean withinRange = false;
Date now = Calendar.getInstance().getTime();
Date serverDate = now;
try {
serverDate = dateFormat.parse(serverValue);
} catch (ParseException e) {
e.printStackTrace();
}
long millis = Math.abs(now.getTime() - serverDate.getTime());
System.out.println("Millis: " + millis);
//1000ms * 60s * 2m
if (millis <= (1000 * 60 * 2)) {
withinRange = true;
}
return withinRange;
}
public static void main(String[] args) {
Test test = new Test();
boolean value = test.plusMinusTwoMins(test.serverValue);
System.out.println("Value: " + value);
boolean value2 = test.plusMinusTwoMins(test.serverValueNew);
System.out.println("Value2: " + value2);
}
}
Say I have two date fields receiveDate and currentDate. I want to check if receiveDate was 5 days before currentDate. What I did was to convert the dates in milliseconds and then compare against 5. Is there a better way of doing so? If so, how and why mine is any less better? Thanks.
Method I wrote -
private static final double DAY_IN_MILLISECONDS = 86400000;
// Param date is the receivedDate
private long getDaysOld(final Date date) {
Calendar suppliedDate = Calendar.getInstance();
suppliedDate.setTime(date);
Calendar today = Calendar.getInstance();
today.setTime(currentDate);
double ageInMillis = (today.getTimeInMillis() - suppliedDate.getTimeInMillis());
double tempDouble;
if(isEqual(ageInMillis, 0.00) || isGreaterThan(Math.abs(ageInMillis), DAY_IN_MILLISECONDS)) {
tempDouble = ageInMillis / DAY_IN_MILLISECONDS;
} else {
tempDouble = DAY_IN_MILLISECONDS / ageInMillis;
}
long ageInDays = Math.round(tempDouble);
return ageInDays;
}
Then I have something like-
long daysOld = getDaysOld(receivedDate) ;
if(daysOld <= 5) {
.... some business code ....
}
give a try to joda-time. Time calculations with the native API is always akwards at best. Joda time makes this type of calculation MUUUCH simpler and will handle time zones pretty well also.
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Test {
private static long DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;
public static void main(String[] args) throws Exception {
//
Date currentDate = getGregorianDate(1990, Calendar.JANUARY, 20);
Date receiveDate = getGregorianDate(1990, Calendar.JANUARY, 23);
//
if (getDifferenceBetweenDates(receiveDate, currentDate) < 5 * DAY_IN_MILLISECONDS) {
System.out.println("Receive date is not so old.");
}
else {
System.out.println("Receive date is very old.");
}
}
private static long getDifferenceBetweenDates(Date date1, Date date2) {
return Math.abs(date1.getTime() - date2.getTime());
}
private static Date getGregorianDate(int year, int month, int date) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(year, month, date);
return calendar.getTime();
}
}
It can be shortened a lot:
int daysOld = (System.currentTimeMillis() - date.getTime()) / DAY_IN_MILLISECONDS;
You can't simply subtract and divide by 24*60*60*1000, because of daylight savings (in which a day could have 23 or 25 hours).
For example, in the UK the clocks moved forward by one hour on 28/03/2010. The difference between 27/03/2010 and 28/03/2010 should be 1 day, but if you follow that approach you will get 0.
You need to take the offset into account:
public static long daysBetween(Date dateEarly, Date dateLater) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(dateEarly);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(dateLater);
long endL = cal2.getTimeInMillis() + cal2.getTimeZone().getOffset( cal2.getTimeInMillis() );
long startL = cal1.getTimeInMillis() + cal1.getTimeZone().getOffset( cal1.getTimeInMillis() );
return (endL - startL) / (24 * 60 * 60 * 1000);
}
public static void main(String[] args) throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Date foo = new Date(2010,02,27);
Date bar= new Date(2010,02,28);
System.out.println(daysBetween(foo,bar)); //prints 1
}
This all depends on what "five days" means. If you receive something monday lunchtime, then on saturday afternoon, did you receive it within five days or not? The elapsed time is greater than five days, but the day you received it is five days ago. Think about how you'd answer that question; now thing about how your mother would answer that question. It might not be the same - I would suggest that most people, particularly non-programmers, count the passing of days by the passing of local midnights. Five o'clock on wednesday morning is a day after eleven thirty on tuesday night, even though it's less than a day (less than a quarter of a day!) later.
So, i think what you want to do is compare just the dates, not the times. You can do this with Calendar by zeroing all the time fields. Given an arrivedDate and a locale (so you can tell when midnight is), i think this is correct:
Calendar deadline = Calendar.getInstance(locale);
deadline.set(Calendar.HOUR_OF_DAY, 0);
deadline.set(Calendar.MINUTE, 0);
deadline.set(Calendar.SECOND, 0);
deadline.set(Calendar.MILLISECOND, 0);
deadline.add(Calendar.DAY_OF_MONTH, 5);
Calendar arrived = Calendar.getInstance(locale);
arrived.setTime(arrivedDate);
deadline.set(Calendar.HOUR_OF_DAY, 0);
deadline.set(Calendar.MINUTE, 0);
deadline.set(Calendar.SECOND, 0);
deadline.set(Calendar.MILLISECOND, 0);
boolean arrivedWithinDeadline = arrived.compareTo(deadline) <= 0;
You should test that thoroughly before actually using it, though.
Below is my method that returns me exact difference in days,
/**
* method to get difference of days between current date and user selected date
* #param selectedDateTime: your date n time
* #param isLocalTimeStamp: defines whether the timestamp d is in local or UTC format
* #return days
*/
public static long getDateDiff(long selectedDateTime, boolean isLocalTimeStamp)
{
long timeOne = Calendar.getInstance().getTime().getTime();
long timeTwo = selectedDateTime;
if(!isLocalTimeStamp)
timeTwo += getLocalToUtcDelta();
long delta = (timeOne - timeTwo) / ONE_DAY;
if(delta == 0 || delta == 1) {
Calendar cal1 = new GregorianCalendar();
cal1.setTimeInMillis(timeOne);
Calendar cal2 = new GregorianCalendar();
cal2.setTimeInMillis(timeTwo);
long dayDiff = cal1.get(Calendar.DAY_OF_MONTH) - cal2.get(Calendar.DAY_OF_MONTH);
return dayDiff;
}
return delta;
}