Implementing TOTP algorithm on JAVA - java

I wanted to implement this algorithm but I am struggling with writing the function that calculates the unix time for UTC time (not local time). For example,
Instant.now().getEpochSecond();
returns unix time according to my local time. But how can I make it work for UTC time? Thank you.

So to be able to get the epoch time in java you would have to use System.currentTimeMillis()
And then dividing this number by 1000 will result in the Unix epoch. A call like this would suffice.
long unixTime = System.currentTimeMillis() / 1000L;

Related

Equivalent of Erlang now() in Java

I am working on a project which requires timestamps for running threads. In Erlang, when we do now() we get something like
{1529,709564,578215} which represent {megaseconds, seconds, microseconds}
since epoch. So, for two processes spawned at the same time, I can get same microseconds value. Is there a way to replicate this function in Java?
I know about Date.getTime() which gives us the milliseconds since epoch time, but it does not serve the purpose since I cannot get a unique microsecond value from it after dividing by order of magnitude.
Any alternative?
System.out.println(Instant.now());
Output just now was:
2018-06-23T05:16:45.768006Z
On the Java 10 on my Mac it gave microsecond precision. Since Java 9 it will on many operating systems, maybe not all. Instant.now() returns an Instant. An Instant is implemented as seconds and nanoseconds since the epoch, and you can get out those individually if you want.

subtracting time in Java

Hello I am trying to create a teacher utility to port over to android OS. However I am running into a little trouble. I would like to create a class called Period. This class would contain the start and end time of that period. ie. Period one starts at 7:45 and ends at 8:45. I would also like to have a method for time left in period. for example it is now 8:10 and there are 35 minutes left. I am able to get the current time from System.currentTimeMillis(). However I am having trouble trying to figure out the best way to store the start and end time of the periods. i have taken a look at the Calendar class in Java and it seems like time is always tied to a date as well as a time. This does not seem to make seance for my application since the end time of the period happens on multiple days and not just on one particular date. Any help understanding this would be a great help. Thanks all
If your goal is to be able to compare the start and end time of the period with the current time, then you need a way to compute the date and time of the period's bounds for today.
So get a Calendar instance for today, set its time to 7:45, and compare the time of the calendar with the current time (same for the upper bound, of course).
To represent each bound, you could simply use an int for the hours and a second int for the minutes.
Check out the JodaTime library. The DateTime object has what you want.
Take a look at JodaTime.
Specifically, Period: http://joda-time.sourceforge.net/key_period.html
Calendar is a king of wrapper around the class Date which has mostly deprecated functions. I've heard that the JodoTime API is great for comparing two timestamps (http://joda-time.sourceforge.net/).
One way to store the start and end time for the periods would be to instantiate an ArrayList of dates so you can compare any given time to the lesson periods.
From what I can tell, you should store the time as a number of seconds (optionally milliseconds) from last midnight. Thus, your period one, 7.45, starts at 45*60 (45 minutes * 60 seconds per minute) + 7*60*60 (7 hours times minutes times seconds!) = 2 700 + 25 200 = 27 900.
Do the same calculation for your end date, and as long as they begin and end on the same day, you can easily subtract the difference and thus get the interval in between. If they do not happen on the same date, then Java's time and date classes are both excellent and a must. These classes essentially work the same algorithm, but do not count the seconds from "last midnight", instead they count the amount of milliseconds from the UNIX epoch time (1 January 1970).

How to get the microseconds from a Date?

I am trying to get microseconds from a Date, but I can't.
Date date = new Date()
No, Date only stores values to millisecond accuracy. If you want microsecond accuracy, you might want to look at JSR-310, or java.sql.Timestamp as a bit of a hack - but don't expect any of the built-in classes such as Calendar and DateFormat to handle anything beyond milliseconds.
If you're trying to perform timing (e.g. for benchmarking) you should use System.nanoTime, but that should only be used for stopwatch-like use cases - it doesn't give you the "current wallclock time" in a meaningful way.
What I do is find the difference between the currentTimeMillis and the nanoTime() at regular intervals (as this drifts quite a bit) and use nanoTime() + OFFSET for a currentTimeNS. (More specificity I use the RDTSC machine code instruction, which comes with even more quibbles ;)
However, its is less accurate than currenTimeMillis() over time which itself can drifts by many milli-seconds in an hour.
It only really useful if you understand its limitations.
To measure time in microseconds you need to use the System.nanoTime() function which will return a time in microseconds based on the most accurate clock available to your system.
To the user this acts in pretty much the same way as System.currentTimeMilis() does for milliseconds, you simply define your start and end times and then negate the difference to find out how long an action took. For example:
long startTime = System.nanoTime();
//Do some kind of processing;
//loop, IO, whatever you want to measure
long endTime = System.nanoTime();
long elapsedTime = endTime - startTime;
The last bit can be shorted, I've left it verbose for simplicity:
long elapsedTime = System.nanoTime() - startTime;
This should not be used to measure real time as it has very little meaning or guarantee that it is even comparable to it. All of the above information is available from the Java API documentation for System.

Compare hours and minutes

I am developing an app based on date and time in java. In this app, my user is allowed to record an video only once per hour. so for this I am storing the previous time has used my app.
So when the user starts my app for the next time, I am comparing the time and if the time interval is more than one hour I must allow my user to record, else I should not allow. How to compare hours and minutes efficiently in java?
Get the system time with
long time = System.currentTimeMillis();
and compare the new time with the old one. One hour means a difference of 1000 * 60 * 60 milliseconds
From #Dalino answer, you may use TimeUnit enum class for time conversions.
long now = System.currentTimeMillis();
long lastVisit = ...; // in milliseconds
if(TimeUnit.MILLISECONDS.toHours(now - lastVisit) > 0) {
// allow
}
Why not just store the time when they exit (or whatever) and then on start up, read the time, add an hour to it, and compare with the current time?
You don't need to compare the actual hours and minutes - just the duration of time between then and now.
Personally I'd suggest using Joda Time for all Java date/time work, but in this case you could just use Date, and add an hour's-worth of milliseconds. Note that you should definitely store a UTC date/time instead of a local one, as otherwise daylight saving changes etc will mess things up.
I would use Joda Period: have a look here

java display Windows UTC time

Windows stores FileTime internally as the number of 100-nanoseconds since 1.1.1601 UTC as a 64bit field, is it possible to get java to print out the current number? Just looking for an example as I can't find a way to do it. I would like to print the number out?
Any help woudl be greatful!
Thanks.
Approximately
long diff1601to1970 = 315532800 * 1000000000; // <-- diff in nanoseconds(1/1/1601 to 1/1/1970)
long currentFrom1970 = System.currentTimeMillis() * 1000000;
long currentFrom1601 = diff1601to1970 + currentFrom1970;
Java doesn't provide direct access to a raw file time, so if you ask for the lastModified time
someFile.lastModified();
You will get the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs
Not every platform tracks the "same" times in relation to a file, and how they track it internally is different. Part of Java's attempt to make a coherent platform out of the differing standards uses polymorphism to translate the platform specific times to the "java standard" under the covers.
Now to convert the millis returned to a java time:
java.util.Date date = new java.util.Date(millis);
From there you can use the standard i/o routines to display and format the date (DateFormat, etc.)
PS. 1/1/1601 was chosen as the epoch by COBOL initially and mimicked by Microsoft (and possibly others). The reason it was chosen is because it's the start of the 400 year Gregorian Calendar cycle at the time the operating system was released. Every 400 years, the pattern of leap years repeats itself.

Categories