I always get 0 when subtracting time - java

So I'm making an app that gets 2 time strings and subtracts them so I can get the amount of time that passed and for some reason, it always returns 0 please help me.
Here is the code I'm using
static String TimeIn() {
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date time = Calendar.getInstance().getTime();
a = format.format(time);
return a;
}
static String TimeOut() {
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date time = Calendar.getInstance().getTime();
b = format.format(time);
return b;
}
static long Duration() throws ParseException {
String a = TimeIn();
String b = TimeOut();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date date1 = format.parse(a);
Date date2 = format.parse(b);
long dur = date2.getTime() - date1.getTime();
return dur / 1000;
}
static String a;
static String b;

Your code gets two times.
After that , you calculate the difference and divide it by 1000.
The problem is that the times are in milliseconds as long values.
The times may be calculated in less than a millisecond and may therefore be equal as long cannot store decimals.
Also the division by 1000 makes it worse as it erases all differences that are smaller than a second.
In other words, the time difference between the call of TimeIn and TimeOut has to be at least one second if the result should not be 0.
[Note]
By convention, method names should start with a lowercase letter in java.

You make one measurement immediately after the other.
Consider the following scenario:
String a = TimeIn();
Thread.sleep(2000L);
String b = TimeOut();
Then the output is: 2

It seems like you call TimeIn right after TimeOut. These execute in under a second, so that your dates (that are only precise to the second) are the same. Putting a Thread.sleep(100000) in between prints the correct duration:
// throw Exception for brevity
static long Duration() throws Exception{
String a=TimeIn();
Thread.sleep(10000);
String b=TimeOut();
// ...
}
For more precise duration measurements use System.currentTimeMillis() or even System.nanoTime():
long then = System.currentTimeMillis();
// do stuff
long duration = System.currentTimeMillis() - then;
This gives you the time in milliseconds. In this example, Duration() runs in 30-50 ms
Also, methods usually start with a small letter, like duration() or timeIn().

The time difference execution of the TimeIn() and TimeOut() is negligible. We can use Thread.sleep();
class Demo {
public static void main(String[] args) throws ParseException, InterruptedException {
System.out.println(Duration());
}
static String TimeIn() throws InterruptedException {
SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss:SSS");
Date time= Calendar.getInstance().getTime();
Thread.sleep(2000);
a=format.format(time);
return a;
}
static String TimeOut(){
SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss:SSS");
Date time= Calendar.getInstance().getTime();
b=format.format(time);
return b;
}
static long Duration() throws ParseException, InterruptedException {
String a=TimeIn();
String b=TimeOut();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss:SSS");
Date date1 = format.parse(a);
Date date2 = format.parse(b);
long dur = date2.getTime() - date1.getTime();
return dur/1000;
}
static String a;
static String b;
}

Related

How to find the duration between two dates in Java

I'm currently using this code to find the difference between a given start and end date:
Let's say start date = "5/31/19 23:59"
and end date = "6/1/19 1:59"
In this case, the difference should be 2 hours, or 120 minutes.
But my solution yields that duration = -1320 minutes.
public class MinimalReproducibleExample {
static SimpleDateFormat fr = new SimpleDateFormat("MM/dd/YY HH:mm");
public static void main(String[] args) throws ParseException {
String start = "5/31/19 23:59";
String end = "6/1/19 1:59";
Date startTime = fr.parse(start);
Date endTime = fr.parse(end);
long diff = endTime.getTime() - startTime.getTime();//as given
long duration = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.format("%d minutes%n", duration);
}
}
Output from the code is:
-1320 minutes

Get current time and check if time has passed a certain period

this code below gets the current time and timezone of the area
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
right now its 1:01 pm (at the time of typing)
what i need help doing is implementing a feature in the code that checks if the current time has passed, for example 1:00PM
but I have no idea where to even start, can you help me out?
Use the Java 8+ Time API class LocalTime:
LocalTime refTime = LocalTime.of(13, 0); // 1:00 PM
// Check if now > refTime, in default time zone
LocalTime now = LocalTime.now();
if (now.isAfter(refTime)) {
// passed
}
// Check if now >= refTime, in pacific time zone
LocalTime now = LocalTime.now(ZoneId.of("America/Los_Angeles"))
if (now.compareTo(refTime) >= 0) {
// passed
}
I see it has already answered with Time, but as a teaching point, if you really wanted to use Date, you could have done something like this:
public static void main(String[] args) {
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
//If you print the date you'll see how it is formatted
//System.out.println(date.toString());
//So you can just split the string and use the segment you want
String[] fullDate = date.toString().split(" ");
String compareAgainstTime = "01:00PM";
System.out.println(isPastTime(fullDate[3],compareAgainstTime));
}
public static boolean isPastTime(String currentTime, String comparedTime) {
//We need to make the comparison time into the same format as the current time: 24H instead of 12H:
//then we'll just convert the time into only minutes to that we can more easily compare;
int comparedHour = comparedTime[-2].equals("AM") ? String.valueOf(comparedTime[0:2]) : String.valueOf(comparedTime[0:2] + 12 );
int comparedMin = String.valueOf(comparedTime[3:5]);
int comparedT = comparedHour*60 + comparedMin;
//obviously currentTime is alredy the correct format; just need to convert to minutes
int currentHour = String.valueOf(currentTime[0:2]);
int currentMin = String.valueOf(currentTime[3:5]);
int currentT = currentHour*60 + currentMin;
return (currentT > comparedT);
}
It's a bit messier, having to muddy into the Strings and whatnot, but it is possible. You would also have to be careful the zero-pad the comparedTime or just check for that in the function

I am trying to calculate difference between two dates in seconds. (Java/Android)

For someone else who might stumble here, the link refered to in this question gives misleading results
My First Date: 1986-04-08. Current Date: 2013-11-28.
Code:
public long seconds(Date date){
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",getResources().getConfiguration().locale).format(Calendar.getInstance().getTime());
String DateStr=String.valueOf(formattedDate);
Date d = null;
try {
d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",getResources().getConfiguration().locale).parse(DateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
java.sql.Date dx = new java.sql.Date(d.getTime());
Date d1 = date;
Date d2 = dx;
t4.setText("BirthDate"+date+"\n Current Date:"+dx);
long seconds = (d2.getTime()-d1.getTime())/1000;
return seconds;
}
However when I check the results here: http://www.calculator.net/age-calculator.html?today=04%2F04%2F1986&ageat=11%2F28%2F2013&x=32&y=10 it gives me a slight different result. I am unsure where I am going wrong.
The online service you link to is wrong: it counts the age as whole days and then assumes that each day is exactly 24 hours long. Most of the time that's correct, but in most places in the world there are days with daylight savings time transitions and timezone transitions, meaning there have been days with 23, 25, or some other number of hours. The number you get from your Java code is more precise.
I think you're somehow mixing java.sql.Date and java.util.Date.
I would try simplifying the code. Something like this.
public class Test012 {
public static void main(String[] args) throws Exception {
System.out.println( seconds() );
System.out.println( seconds2() );
System.out.println( days3() );
}
public static long seconds() throws Exception {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date d1 = sdf.parse("1986-04-08");
java.util.Date d2 = sdf.parse("2013-11-28");
return ( d2.getTime() - d1.getTime() ) / 1000;
}
public static long seconds2() throws Exception {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date d1 = sdf.parse("1986-04-08");
java.util.Date d2 = new java.util.Date();
return ( d2.getTime() - d1.getTime() ) / 1000;
}
public static long days3() throws Exception {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date d1 = sdf.parse("2008-01-01");
java.util.Date d2 = sdf.parse("2009-01-01");
return ( d2.getTime() - d1.getTime() ) / 1000 / 60 / 60 / 24;
}
}
I also tried
select datediff(ss, '4/8/1986', '11/28/2013') --- US date format
in SQL Server and it prints the same thing as this java program,
it prints 872294400. So this seems to be the correct value.
Are you sure the dates coming on your input are the right ones
(are equal to those I hardcoded in my test program)?
I would check that too.
Also, are you sure your dates have zero time parts? That's what the link/service you posted assumes.
Try this code:--
public static long secondsBetween(Calendar startDate, Calendar endDate) {
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween*24*3600;
}
Hope it helps you.. Enjoy..!

convert a string of time to 24 hour format

I have a string holding a start time and an end time in this format 8:30AM - 9:30PM I want to be able to strip out the AM - and the PM and convert all the times to 24 hour format so 9:30PM would really be 21:30 and also have both the times stored in 2 different variables, I know how to strip the string into substrings but Im not sure about the conversion, this is what I have so far. the time variable starts out holding 8:30AM - 9:30PM.
String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM"
String startTime;
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"
String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"
Working code (considering that you managed to split the Strings):
public class App {
public static void main(String[] args) {
try {
System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
System.out.println(convertTo24HoursFormat("9:30PM")); // 21:30
} catch (ParseException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Replace with KK:mma if you want 0-11 interval
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
// Replace with kk:mm if you want 1-24 interval
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");
public static String convertTo24HoursFormat(String twelveHourTime)
throws ParseException {
return TWENTY_FOUR_TF.format(
TWELVE_TF.parse(twelveHourTime));
}
}
Now that I think about it, SimpleDateFormat, H h K k can be confusing.
Cheers.
You need to use: SimpleDateFormat
And can refer this tutorial: Formatting hour using SimpleDateFormat
Example:
//create Date object
Date date = new Date();
//formatting hour in h (1-12 in AM/PM) format like 1, 2..12.
String strDateFormat = "h";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println("hour in h format : " + sdf.format(date));
I wouldn't reinvent the wheel (unless you are doing this as a school project or some such).
Just get a date object out of your time stamp and then you can generate whatever format you want with this: SimpleDateFormat
[edited to address your specific request]
if you absolutely need to work from your own unique strings, then you'll do something like this (I don't know exactly what your strings look like... you're using offsets like 85, which means nothing out of context).
I didn't check this for bugs, but this is approximately what you want...
myStr = timestampString.toLowerCase(); //something like 8:30am
boolean add12 = (myStr.indexOf("pm") != -1)?true:false;
//convert hour to int
int hour = Integer.parseInt(myStr.split(":")[0]);
int minutes = Integer.parseInt( myStr.split(":")[1].replaceAll("\\D+","").replaceAll("^0+","") ); //get the letters out of the minute part and get a number out of that, also, strip out leading zeros
int militaryTime = hour + (add12)? 12:0;
if(!add12 && militaryTime == 12)
militaryTime = 0; //account for 12am
//dont' forget to add the leading zeros back in as you assemble your string
With Joda Time, the code looks like:
DateTimeFormatter formatter12 = DateTimeFormat.forPattern("K:mma");
DateTime begin = formatter12.parseDateTime(beginTime);
DateTime end = formatter12.parseDateTime(endTime);
DateTimeFormatter formatter24 = DateTimeFormat.forPattern("k:mma");
String begin24 = formatter24.print(begin);
String end24 = formatter24.print(end);
I should like to contribute the modern answer
DateTimeFormatter twelveHourFormatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
String time = "8:30AM - 9:30PM";
String[] times = time.split(" - ");
LocalTime start = LocalTime.parse(times[0], twelveHourFormatter);
System.out.println(start.toString());
LocalTime end = LocalTime.parse(times[1], twelveHourFormatter);
System.out.println(end.toString());
This prints:
08:30
21:30
I am using java.time, the modern Java date and time API. The SimpleDateFormat class used in many of the other answers is long outdated and was always troublesome. java.time is so much nicer to work with than the date-time classes from the 1990’s. A LocalTime is a time of day without a date (and without time zone), so suits your need much better than an old-fashioned Date.
Link: Oracle tutorial: Date Time explaining how to use java.time.
24 hour time adds 12 to any time greater than 12pm so that 1pm is 13 and so on until 24 or 12am. Here is the sudo code:
if(hour <= 12)
{
hour = hour + 12;
}
All the below lines will works when
String str="07:05:45PM";
and when you call timeConversion(str) and want to convert to 24 hours format..
public class TimeConversion {
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");
static String timeConversion(String s) {
String str = null;
try {
str= TWENTY_FOUR_TF.format(
TWELVE_TF.parse(s));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public static void main(String[] args) throws ParseException {
String str="07:05:45PM";
System.out.println(timeConversion(str));
}
}

Java Timestamp Comparison

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);
}
}

Categories