Get time of a calendar in nanoseconds - java

Since the Java doc tell me, not to use System.currentTimeMillis for comparison, I started using System.nanoTime which is fine.
But I ran into some problems, I have to compare events which are in the past.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, xyz);
cal.getTimeMillis();
works fine to get the time in milliseconds, but converting it to nanoseconds (by multiplying it with 1000000) is far to inaccurate.
How can I get time of a event in the past in milliseconds?

The Calendar class in Java doesn't contain nanosecond information. So you can't get that.
You need to store the nanoseconds as long for the event you want to compare later if you need that detail.: you can't do that too, the nanoTime() is not a representation of current time, but you may still store that to evaluate elapsed time of old processes.

What data type are you using for the multiplication by 1,000,000 ? Perhaps you should use a BigDecimal, which would be accurate enough for you.

Related

Converting epoch time to the hour

Given an epoch time: eg (1513213212) I should get 1 since its 1 am right now UTC. How would I go about converting it into the hour of the day? Is it possible to do it just using math (division, mod)?
It would be close to impossible to do it by using maths only. (Leap year and all). It's better to use established APIs which will do all the hard work.
You can use following method to do this.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1513213212* 1000L);
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(cal.get(Calendar.HOUR));//12 hour clock
System.out.println(cal.get(Calendar.HOUR_OF_DAY));//24 hour clock
Use java.time, the modern Java date and time API also known as JSR-310:
LocalTime timeOfDay = Instant.ofEpochSecond(1513213212L)
.atOffset(ZoneOffset.UTC)
.toLocalTime();
System.out.println(timeOfDay);
int hourOfDay = timeOfDay.getHour();
System.out.println(hourOfDay);
This prints:
01:00:12
1
Even if you just wanted to do the math, I would still prefer to use standard library methods for it:
long epochSeconds = 1513213212L;
// convert the seconds to days and back to seconds to get the seconds in a whole number of days
long secondsInWholeDays = TimeUnit.DAYS.toSeconds(TimeUnit.SECONDS.toDays(epochSeconds));
long hourOfDay = TimeUnit.SECONDS.toHours(epochSeconds - secondsInWholeDays);
System.out.println(hourOfDay);
This too prints 1.
Your intention was “Given an epoch time: eg (1513213212) I should get 1 since it’s 1 AM right now UTC.” Which of the above code snippets in your opinion most clearly expresses this intention? This is what I would use for making my pick.
While MadProgrammer is surely correct in his/her comment that date and time arithmetic is complicated and that you should therefore leave it to the date and time API, I believe that this is one of the rare cases where not too complicated math gives the correct answer. It depends on it being safe to ignore the issue of leap seconds, and if going for the math solution, you should make sure to check this assumption. Personally I would not use it anyway.

Time difference between two calendar dates

I am looking for to calculate the time difference between two calendar dates and need the result difference in minutes. Below is what I am trying but it says: can't apply - operator. My page.getLastModified().getTime() gives me Calendar object. Any idea how can I achieve this.
long lastModified = page.getLastModified().getTime() - Calendar.getInstance().getTime();
getTime() returns Date instance and there is no overloaded - operator for Date. You may try with getTimeInMillis() to get difference milliseconds between two dates. You can later convert these milliseconds to minutes for instance with
TimeUnit.MILLISECONDS.toMinutes(durationInMillis)
I generally make use of
Joda Time
Simply because it has functions to give you the time between two dates.
Read into this previous post Usage for more info on how to.

What is the best way to save epoch time in Java?

I'm using the epoch time format to save date. My problem is Java Long is enough to handle this or should I consider Java BigInteger to handle the epoch time?
Assuming you mean UNIX epoch, Java long is more then enough. UNIX epoch is number of seconds since January 1, 1970 and is stored (in UNIX) as a 32-bit int.
Yes, a long is sufficient. But in terms of the best way, consider using native types.
In Java <= 7, java.util.Date is designed for this purpose. It has millisecond precision.
In Java >= 8, java.time.Instant is designed for this purpose. It has nanosecond precision.
In Java you can get the milliseconds since the UNIX Epoch with System.currentTimeMillis() which returns a long, so there's no reason to consider something else.
If by epoch time, you mean seconds since 1970, long will of course do the job, as it can represent millis as well up until end of time ;-)
My point is that you can might integer instead. it will represent time in secs since 1970 up to year 2038.
If you don't need to represent time before now, consider using a special format like stated here. This will help you represent a wider future range.
Another option for representing time only after now, is starting the measure since 2021, by subtracting the seconds: nowSecs - 2021Secs.

C# Ticks convert to java util date; date is 5 hours behind why?

I need help. I have been trying to figure out why java util date is 5 hours behind after converting from C# ticks.
in C#, the date is 6/8/2013 11:02:07 AM, I convert this date into ticks then pass it to java as long.
code snippet:
taken:
- long TICKS_AT_EPOCH = 621355968000000000L;
- long TICKS_PER_MILLISECOND = 10000;
java.util.Date date = new java.util.Date((ctime - TICKS_AT_EPOCH) / TICKS_PER_MILLISECOND);
Now java util date is Sat Jun 08 06:02:07 CDT 2013
Notice that the hour is 5 hours difference.
Any suggestions why?
You are constructing a java.util.Date based on milliseconds since 1/1/1970 UTC. You appear to be correcting from the fact that .net's System.DateTime.Ticks are based on 1/1/0001 and are 10,000 ticks to a millisecond. That is correct, but you have forgotten to adjust to UTC.
In .Net, the value coming from DateTime.Ticks is highly dependent on the DateTime.Kind property. There are three possible kinds of DateTime values.
DateTimeKind.Utc - This kind means that the value represents UTC time. It usually comes from a call to DateTime.UtcNow, but can also be constructed directly, and often is. For example, you might be retrieving UTC times from a database. You can feed the ticks from here directly into your conversion, and it will work.
DateTimeKind.Local - This usually comes from a call to DateTime.Now. The values are representative of the local time zone. You will need to convert to UTC before checking the ticks. You can do the following:
DateTime dt = DateTime.Now;
int utcTicks = dt.ToUniversalTime().Ticks;
Be aware that if the time happens during a daylight saving "fall-back" style transition, the result might be incorrect. The DateTime class has no idea about time zones. It just reflects the current local clock. If the value in dt is ambiguous, ToUniversalTime() will assume that the value is representative of standard time, even if you just retrieved it while in daylight time. This is just one of the many confusing and probablematic aspects of DateTime in .net.
DateTimeKind.Unspecified - This is the most common kind of DateTime you will encounter, and usually comes from DateTime.Parse() or a constructor like new DateTime(...). Unfortunately, there is nothing in here that will tell you about the time zone these dates are representative of. You can still try calling .ToUniversalTime(), but the framework will make the assumption that these times are representative of your local time zone, as if the kind was Local. That assumption could be completely wrong, depending on how you sourced the data. There really is no safe way to transform an Unspecified DateTime to a UTC value (ticks or otherwise).
There are some solutions, such as using DateTimeOffset instead of DateTime, or using the Noda Time library instead of the built-in types. You can read more about these problems here and here.
The time is not 5 hours behind, it's exactly the same time. The problem is with the way you print it.
You need to tell C# and Java to use the same time-zone when converting the date to string. One of them is using UTC and the other CDT.
java.util.date automatically corrects for your time zone. See this question: How to set time zone of a java.util.Date?
The ctime is UTC (Universal Coordinated Time), which is a time standard referenced to Greenwich. You're expressing your time in Central time. There's your difference.

Joda Time's Period.getMillis returns inaccurate number

I ran into a strange issue with JodaTime's Period class. I come to the point where I've instantiated a Period object, which is being printed as: PT8M19.966S, which clearly says 8 minutes and 19 seconds (this is correct at this point), and I call Period.toMillis. The result I get is some random number, such as 968, or 152, numbers that clearly are not what this method is supposed to return. So I wonder if it is some kind of bug, or misuse from my side.
You mean getMillis()? The javadoc says it only returns the millisecond part of the period, not the period's duration in milliseconds.
As suggested by Louis above, you should convert Period to Duration first, and then get its milliseconds:
long millis = period.toStandardDuration().getMillis();
Main reason for that is that ReadablePeriod doesn't know exactly how many milliseconds it has inside, until you apply it to a calendar. For example, how many milliseconds are in one month? We can't get an answer until this month is applied to a calendar.

Categories

Resources