I have two times variable as string
want to find the mean time. please help me
inTime = shift.getInTime()+":00";
outTime = shift.getOutTime()+":00";
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date d1=df.parse(inTime);
Date d2 = df.parse(outTime);
long date1InMilSec=d1.getTime();
long date2InMilSec=d2.getTime();
long half =date1InMilSec + ((date2InMilSec - date1InMilSec) / 2);
long minute = (half / (1000 * 60)) % 60;
long hour = (half / (1000 * 60 * 60)) % 24;
String time = String.format("%02d:%02d", hour, minute);
First of all, if I use your code and set fixed time values, then I get 11:30:00 instead of your 07:00:00, so there is maybe something else wrong with inTime and outTime.
Since I get 11:30:00 there is maybe something wrong with your calculation of hour and minute, but I won't bother that. Let's use a new Date instance to do the conversion:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date d1 = df.parse("09:30:00");
Date d2 = df.parse("15:30:00");
long date1InMilSec = d1.getTime();
long date2InMilSec = d2.getTime();
long half = date1InMilSec + ((date2InMilSec - date1InMilSec) / 2);
Date meanTime = new Date(half); // new Date instance, instead of own calculation
String time = df.format(meanTime);
System.out.println(time);
This code prints:
12:30:00
String inTime = "09:30:00";
String outTime = "15:30:00";
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date dateIn = df.parse(inTime);
Date dateOut = df.parse(outTime);
long dateInMill = dateIn.getTime();
long dateOutMill = dateOut.getTime();
long dateMiddleMill = dateInMill + ((dateOutMill - dateInMill) / 2);
Date dateMiddle = new Date(dateMiddleMill);
System.out.println(df.format(dateMiddle));
Related
I'm making a simple app where i get I get time is as a long and the current time from calendar.getInstance() (the current time).
I would like to check the difference in days between the 2 dates.
Long date1 = 1499175346756l;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yy.HH.mm.ss");
Calendar c = Calendar.getInstance();
String formattedDate = dateFormat.format(c.getTime());
If i am not wrong, you have both the dates in "Long type", than you can try the following code
Calendar firstDate = Calendar.getInstance();
Calendar lastDate = Calendar.getInstance();
Date startDate = firstDate.getTime();
Date endDate = lastDate.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
I am working on creating an android quiz game. I want to implement timer for each level to calculate how fast the user can answer all the questions. between each level there is an activity which i want to show the time taken to answer the quiz in the previous level before proceed into the next level. Can I get a guide on how to implement this? Thank you in advance
You can do something like this, when the user starts quiz and enters into your first level, then inside onCreate take start time like this:
Calendar calendar;
SimpleDateFormat df;
String template = "yyyy-MM-dd HH:mm:ss";
calendar = Calendar.getInstance();
df = new SimpleDateFormat(template, Locale.getDefault());
//this will give you the start time
String startTime = df.format(calendar.getTime());
//when user finishes up the level again record the finish time
String finishTime = df.format(calendar.getTime());
//then compare the two times
Date d1 = null;
Date d2 = null;
try {
d1 = df.parse(startTime);
d2 = df.parse(finishTime);
} catch (ParseException e) {
e.printStackTrace();
}
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
Hope it helps!!
I have 2 string in java (HH:MM:SS) please take note this is not time, but duration, i used end time - start time to get these values:
Case1:
duration1 = "12:04:45";
duration2 = "13:04:45";
Expected result: duration1 - duration 2 = "-1:00:00" (Note that there is negative)
Case2:
duration1 = "15:13:32";
duration2 = "12:04:45";
Expected result: duration1 - duration 2 = "3:08:47"
How can i do that? My attempt for the Case1 (codes modified from Java add dates of format dd:HH:mm:ss):
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String s1 = "12:04:45";
String s2 = "13:04:45";
Date d1 = format.parse(s1);
Date d2 = format.parse(s2);
int sec = d1.getSeconds() - d2.getSeconds();
int min = d1.getMinutes() - d2.getMinutes();
int hr = d1.getHours() - d2.getHours();
Time sum = new Time(hr, min, sec);
System.out.println(sum); // Output: 23:00:00 which is wrong
Using LocalTime or date calculations like some people suggest doesn't work if your period involved more than 24 hours since that doesn't fit in a day.
If you don't have Java 8, you can use JodaTime. I've just checked that this code also works with JodaTime 1.6.2, which is the last version that still works with JDK 1.4.2.
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways().minimumPrintedDigits(2)
.appendHours().appendSuffix(":").appendMinutes().appendSuffix(":").appendSeconds()
.toFormatter();
Period period1 = formatter.parsePeriod("12:04:45");
Period period2 = formatter.parsePeriod("13:04:45");
Period difference1 = period1.minus(period2).normalizedStandard();
System.out.println(formatter.print(difference1));
Period period3 = formatter.parsePeriod("15:13:32");
Period period4 = formatter.parsePeriod("12:04:45");
Period difference2 = period3.minus(period4).normalizedStandard();
System.out.println(formatter.print(difference2));
Output:
-01:00:00
03:08:47
JodaTime:
Version 1.6.2 source: https://github.com/JodaOrg/joda-time/releases/tag/v1.6.2
Version 1.6.2 Maven Jar artifact: http://mvnrepository.com/artifact/joda-time/joda-time/1.6.2
With the Java time API you could use a Duration to calculate the duration and format it as you want:
String s1 = "12:04:45";
String s2 = "13:04:45";
LocalTime t1 = LocalTime.parse(s1);
LocalTime t2 = LocalTime.parse(s2);
Duration d = Duration.between(t2, t1);
System.out.println(d); //PT-1H
If you want to print it as -1:00:00 you will need to tweak the output format. It could look like this:
private static String toHHMMSS(Duration d) {
long hours = d.toHours();
int minutes = (int) (d.toMinutes() % 60);
int secs = (int) (d.getSeconds() % 60);
return hours + ":" + minutes + ":" + secs;
}
Use Calendar to calculate the time difference.
You can query each field and/or format as a time string as this example shows:
private Calendar getTimeDiffDate(Date d1, Date d2) {
Calendar c = Calendar.getInstance();
c.setTime(new Date(d1.getTime()-d2.getTime()));
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// Format as a time string:
String formattedTime = formatter.format(c.getTime());
System.out.println("formattedTime: "+formattedTime);
// Query by each field:
System.out.println("Hours: "+c.get(Calendar.HOUR));
System.out.println("Minutes: "+c.get(Calendar.MINUTE));
System.out.println("Seconds: "+c.get(Calendar.SECOND));
return c;
}
I'd like to compare two dates in a string format and return the result in HH:MM:SS:SSS as a String.
When i try running the following with a startDate of 15 Jul 2013 17:08:34.903 and endDate of
15 Jul 2013 17:08:51.247 I'd expect to see a result of 00:00:16.344. Instead i'm getting a diff of 01:00:16.344. Any ideas why this is happening??
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("d MMM yyyy HH:mm:ss.SSS");
private static final SimpleDateFormat DATE_FORMAT_HH_MM_SS = new SimpleDateFormat("HH:mm:ss.SSS");
public String calculateDuration(String startDateStr, String endDateStr){
String methodName = "calculateDuration";
try {
Date startDate = DATE_FORMAT.parse(startDateStr);
Date endDate = DATE_FORMAT.parse(endDateStr);
long diff = endDate.getTime() - startDate.getTime();
return DATE_FORMAT_HH_MM_SS.format(diff);
The JDK Date API is horrible. I recommend using Joda Time library but if you must use JDK Date API try this code:
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"d MMM yyyy HH:mm:ss.SSS");
public String calculateDuration(String startDateStr, String endDateStr)
throws ParseException {
String methodName = "calculateDuration";
Date startDate = DATE_FORMAT.parse(startDateStr);
Date endDate = DATE_FORMAT.parse(endDateStr);
// in milliseconds
long diff = endDate.getTime() - startDate.getTime();
long diffMiliseconds = diff % 1000;
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
return String.format("%02d:%02d:%02d.%02d", diffHours, diffMinutes,
diffSeconds, diffMiliseconds);
}
Since in the comments you say that you're simply measuring running time for an application, don't involve Date, SimpleDateFormat, or Calendar at all.
long tic = System.nanoTime();
...is all you need. Don't use a cannon to kill a mosquito when you have a fly swatter on hand.
You've not initialized your SimpleDateFormat formatter with a Calendar object, so it is using a default one to do the mapping. I am guessing that this default Calendar is recognizing DST. This is not manifest when you .parse() the datetimes, because the DST adjustment cancels out in the subtraction.
When you convert the result to HMS format, the formatter again applies the DST adjustment. Since there is no subtraction in this step, it appears in your result.
It does seem to me that whenever anybody has a date arithmetic question, the rubber-stamp, knee-jerk reflex response is "use JodaTime." We all love JodaTime; it is a well-crafted API. But using it is still an external dependency and unless you -need- it you should not use it. In my opinion, for this situation you do not need JodaTime at all ... you only need the Java Calendar API to parse your datetimes into Dates. And that's all you need it for.
Once you have the difference in milliseconds, you really should avoid using a formatter to convert the result back. Using simple arithmetic will be far more performant:
private static final SimpleDateFormat DATE_FORMAT =
new SimpleDateFormat("d MMM yyyy HH:mm:ss.SSS");
private static final int DAYS = 0;
private static final int HOURS = 1;
private static final int MINUTES = 2;
private static final int SECONDS = 3;
private static final int MILLIS = 4;
private final int[] result = new int[MILLIS];
public String calculateDuration(String startDateStr, String endDateStr){
try {
Date startDate = DATE_FORMAT.parse(startDateStr);
Date endDate = DATE_FORMAT.parse(endDateStr);
} catch (Exception e) { /* exception processing */ }
long diff = endDate.getTime() - startDate.getTime();
double d;
for (int i = DAYS; i <= MILLIS; i++) {
switch(i) {
case DAYS:
d = ((double) diff) / (86400.0 * 1000.0);
break;
case HOURS:
d = d * 24.0; break;
case MINUTES: case SECONDS:
d = d * 60.0; break;
case MILLIS:
d = d * 1000.0; break;
}
result[i] = (int) Math.floor(d);
d = d - (double) result[i];
}
At the conclusion of this last for loop, the array result contains integers that correspond to the number of DAYS, HOURS, MINUTES, SECONDS, and MILLIS derived from your date subtraction. No objects need to be created, allocated, or invoked in order to get this result. You can now easily use the String.format() function to put these integers into the string format of your choosing.
I cant quite figure out what the format should be to parse this date. Its a millisecond value followed by timezone. thx.
// so far tried: "S Z"
// "SSSSSSSSSSS-ZZZZ",
// "SSSSSSSSSSS-Z",
// etc.
Format formatter = new SimpleDateFormat("SSSSSSSSSSSS Z", Locale.CANADA);
// source string looks like this /Date(928164000000-0400)/
String temp = jsonUserObj.getString("DateOfBirth").substring(6, 6+17);
System.err.println("got date="+temp);
Date date = (Date) formatter.parseObject(temp);
You can do it without parser.
String[] parts = new String[]{temp.substring(0, temp.indexOf('-')), temp.substring(temp.indexOf('-') + 1)};
long millis = Long.parseLong(parts[0]);
parts[1] = parts[1].replaceAll("^0*(\\-?[0-9]*)$", "$1");
int timeZone = Integer.parseInt(parts[1]);
int rawOffset = (timeZone / 100) * 3600000 + (timeZone % 100);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis);
cal.setTimeZone(new SimpleTimeZone(rawOffset, "GMT"));
SimpleDateFormat expects a milliseconds value < 1000, as it expects you would increment seconds, then minutes, etc, for larger values.
You'll need to convert the value first; this post might help: Unix epoch time to Java Date object