I have been doing this exercise and this is the code
import java.time.*;
import java.util.*;
public class Exercise31 {
public static void main(String[] args){
LocalDateTime dateTime = LocalDateTime.of(2016, 9, 16, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.now();
int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano();
long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds();
long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis();
long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes();
long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
System.out.printf("\nDifference is %d Hours, %d Minutes, %d Milli, %d Seconds and %d Nano\n\n",
diffInHours, diffInMinutes, diffInMilli, diffInSeconds, diffInNano );
}
}
Doesnt nanoseconds have to use long instead of int because the nanoseconds in the range?
That's because like documentation says, we have a duration which consist of two fields, one is seconds and the other one is nanos.
So when you ask for duration between, you get 2 values :
diff = seconds + nanos
So in this case, nanos only count up to 999,999,999 (0.99... seconds), so integer is enough.
So ...
If you need duration in nanos, you'll have to do something like this :
Long totalDurationNanos = (duration.getSeconds() * 1_000_000_000f) + duration.getNanos();
EDIT :
As mentioned in comments, there is an easier way in your case :
Both
java.time.Duration.between(dateTime, dateTime2).toNanos()
And
ChronoUnit.NANOS.between(dateTime, dateTime2)
would output you long formatted nanosecond duration
getNano() JavaDocs:
Returns:
the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
Related
I seem to have a logic error in my code. The time now is: 14:38, but
my code says 18:38. I know there's a Calendar class I could use, but I want to
know why this code was wrong.
Code below:
public class welcome{
public static void main(String args[]){
//get total milliseconds since 1970
long total_millisec = System.currentTimeMillis();
// compute total seconds since 1970
long total_sec = total_millisec / 1000;
//compute current second
long current_sec = total_sec % 60;
//compute total minutes since epoch
long total_mins = total_sec / 60;
//compute current minute
long current_min = total_mins % 60;
//compute total hours
long total_hours = total_mins / 60;
//compute current hour
long current_hour = total_hours % 24;
System.out.println("Time is: "+current_hour+":"+current_min+":"
+current_sec);
}
}
When you perform your calculation, it's presumed that System.currentTimeMillis() returns difference in milliseconds between midnight of 1st January of 1970 (which is 1970-01-01 00:00) and current time. Try to evaluate the base date in your system and see what it'll be:
System.out.println("" + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(new java.util.Date(0)));
it might return something like 1969-12-31 19:00 and this is not the midnight.
System.currentTimeMillis() returns the same as expression:
long currentTime = new java.util.Date().getTime() - new java.util.Date(0).getTime();
I need to get the days,hours, minutes, seconds from current time till 2038.I am having issues with the output.
public class Assignment1 {
public static void main(String[] args) {
long now = System.currentTimeMillis();
long y2k38 = (long) Math.pow(2, 31)*1000;
long diffmillis = y2k38-now;
long diffsec = (y2k38-now)/1000;
long diffmin = diffsec/60;
long diffhours = diffmin/60;
long diffdays = diffhours/24;
System.out.printf(
"Y2K38 will occur in %d days.\n"+
"Y2K38 will occur in %d hours.\n"+
"Y2K38 will occur in %d minutes.\n"+
"Y2K38 will occur in %d seconds.\n",
(diffdays%24),(diffhours%60), (diffmin%60),(diffsec%60));
}
}
Your main issue is that your diffdays, diffhours, diffmin, and diffsec are all just constants that don't actually interact with the current timestamp, so y2k38-diffdays, y2k38-diffhours, and y2k38-diffmin are simply constants subtracting constants.
You will likely want to calculate the number of milliseconds until 2038 with y2k38-now, and then convert up to the units you want from there.
For example, (y2k38-now)/1000 should give you seconds until 2038, (y2k38-now)/(60*1000) should give you minutes, etc.
I want to calculate difference between two times which is calculate correctly then i have to half it so i divide it with 2 results are okay. but when i am trying to add the timdedifferencemillis to startTime its not giving me the correct result...
starttime= 05:53
endtime= 17:57
i want results 11:55
but my code giving me 06:55
please help.....
protected String transitTime2(String endtime, String starttime) {
SimpleDateFormat dt = new SimpleDateFormat("hh:mm");
Date startTime = null;
Date endTime;
long timdedifferencemillis = 0;
try {
startTime = dt.parse(starttime);
endTime = dt.parse(endtime);
long diff=startTime.getTime();
timdedifferencemillis = (endTime.getTime() - startTime.getTime())/2;
//timdedifferencemillis
} catch (ParseException e) {
e.printStackTrace();
}
long timdedifferencemillis1=startTime.getTime()+timdedifferencemillis;
int minutes = Math
.abs((int) ((timdedifferencemillis1 / (1000 * 60)) % 60));
int hours = Math
.abs((int) ((timdedifferencemillis1 / (1000 * 60 * 60)) % 24));
String hmp = String.format("%02d %02d ", hours, minutes);
return hmp;
}
The problem is probably time zone; when you parse endtime and starttime initially, by default (in the absence of an explicit time zone indicated in the format string and represented in the input), Java assumes that the times provided are relative to the local time zone of the system. Then, when you call getTime(), it returns
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object
One solution is to tell your SimpleDateFormat object to assume that all strings it parses are in GMT, rather than in the local time zone. Try adding this line after you initialize dt, but before calling dt.parse(...):
dt.setTimeZone(TimeZone.getTimeZone("GMT"));
This is quite easy to do with the new java.time API in Java 8 or with the JODA Time library:
import java.time.Duration;
import java.time.LocalTime;
public class TimeDiff {
public static void main(String[] args) {
LocalTime start = LocalTime.parse("05:53");
LocalTime end = LocalTime.parse("17:57");
// find the duration between the start and end times
Duration duration = Duration.between(start, end);
// add half the duration to the start time to find the midpoint
LocalTime midPoint = start.plus(duration.dividedBy(2));
System.out.println(midPoint);
}
}
Output:
11:55
By using LocalTime objects, you avoid any problems with time zones.
I think the problem is the types "long" and "int" in your code ;when we divide with 2 ( long timdedifferencemillis )the result must be "double".
This is my first oportunity to play with the "new" java.time package from Java 8.
I need to get the total elapsed time, something like:
1 day, 2h:3m:4s 5ms
I know that have 2 TemporalAmount implementations for intervals:
- Period for years, months and days
- Duration for hours, minutes, seconds, milliseconds and nanoseconds
There's a way to mix these two or something more straightforward than "do math"?
That was the best I could do until now:
(Updated with a new improved version)
LocalDateTime start = LocalDateTime.now();
// Forcing a long time execution to measure
LocalDateTime end = start
.plusDays(1)
.plusHours(2)
.plusMinutes(3)
.plusSeconds(4)
.plusNanos(5000);
LocalDateTime elapsed = end
.minusDays(start.getDayOfYear())
.minusHours(start.getHour())
.minusMinutes(start.getMinute())
.minusSeconds(start.getSecond())
.minusNanos(start.getNano());
Period period = Period.between(start.toLocalDate(), end.toLocalDate());
long days = period.getDays();
long hours = elapsed.getHour();
long minutes = elapsed.getMinute();
long seconds = elapsed.getSecond();
long milliseconds = elapsed.getNano() / 1000;
StringBuilder msg = new StringBuilder();
msg.append(seconds);
msg.append("s ");
msg.append(milliseconds);
msg.append("ms");
if(minutes > 0) {
msg.insert(0, "m:");
msg.insert(0, minutes);
}
if(hours > 0) {
msg.insert(0, "h:");
msg.insert(0, hours);
}
if(days > 0) {
msg.insert(0, days == 1 ? " day, " : " days, ");
msg.insert(0, days);
}
System.out.println(msg.toString());
Thanks for your time =)
Seems like you need the PeriodFormatter from JodaTime. See below links:
How to format a duration in java? (e.g format H:MM:SS)
Formatting a Duration in Java 8 / jsr310
Given these two, I suggest using JodaTime for Duration.
long startTime = System.nanoTime();
long startTimer = System.currentTimeMillis();
M = app.decriptare_simpla(C);
long endTime = System.nanoTime();
long stopTimer = System.currentTimeMillis();
//mesajul initial dupa decriptare
System.out.println("M : " + M.toString());
System.out.println("Decriptarea a durat: " + (endTime - startTime));
System.out.println("Decriptarea a durat: " + (stopTimer - startTimer));
This gave me:
Decriptarea a durat: 14811776
Decriptarea a durat: 15
What I want to ask is how much of a second are those 2 numbers? I mean are they, 0.15, 0.015, 0.0015...? I'd like to print them in that manner, not as an long but don't know how many decimals to add. Same question for the other number.
The conversions follow the usual rules for Standard SI Units:
long nanoSeconds = ...
double microSeconds = nanoSeconds / 1e3;
double milliSeconds = microSeconds / 1e3;
double seconds = milliSeconds / 1e3;
// Shortcuts:
double milliSeconds = nanoSeconds / 1e6;
double sconds = nanoSeconds / 1e9;
For some conversions, you can also have a look at the TimeUnit class: It allows conversions between values in different time units, for example
long microSeconds = NANOSECONDS.toMicros(nanoSeconds);
However, it unfortunately does not allow time spans given in double precision, but only as long values.
An aside, also mentioned in the comments: Measuring time spans in the order of 10-15ms usually makes no sense due to the limited resolution of the internal timer.
Have you tried like this
System.out.println(TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS));
System.out.println(TimeUnit.SECONDS.convert((stopTimer - startTimer), TimeUnit.MILLISECONDS));