epoch time stamp , find number of days - java

i am trying to find number of days from todays date from the below epoch timestamp:-
1560593315387
like this :
System.out.println(ChronoUnit.DAYS.between(Instant.ofEpochSecond(1558353632),Instant.now()));
It is working fine for 1558353632 but for 1560593315387 it cannot convert and not giving expected results.

1560593315387 looks to be milliseconds, not seconds, so use Instant.ofEpochMilli.
It is also too long (hah!) to fit into an int, so you have to use a long literal instead (with an L at the end).
ChronoUnit.DAYS.between(Instant.ofEpochMilli(1560593315387L), Instant.now())

Please do
int seconds = (int) 1560593315387l / 1000;// (millisecond to senconds conversion)
System.out.println(ChronoUnit.DAYS.between(Instant.ofEpochSecond(seconds), Instant.now()));

Related

Get 12 hours before and after current time

I'm having an issue working with time in Java. I don't really understand how to efficiently solve comparing the time of now and 12 hours before and after
I get a set of starting times for a show from an API and then compare that starting time with LocalTime.now(). It looks something like this:
SimpleDateFormat sdt = new SimpleDateFormat("HH:mm:ss");
String temp = sdt.format(Local.time(now));
LocalTime secondTime = LocalTime.parse(parts1[0]);
LocalTime firstTime = LocalTime.parse(temp);
int diff = (int) ((MINUTES.between(firstDay, secondDay) + 1440) % 1440);
if(diff <= 720){
return true;
}
Where my idea is that if the difference between the two times is smaller than 720 minutes (12 hours) I should get the correct output. And this works for the 12 hours before now. I thought I might need to swap the parameters of .between, to get the other side of the day. That counts it completely wrong (If the time now is 15:00:00 it would accept all the times until 22:00:00 the same day). Is this just a really bad way of comparing two times? Or is it just my math that lacks understanding of what I'm trying to do?
Thanks
Using the 'new' (not that new) Java 8 time API:
Instant now = Instant.now();
Instant hoursAfter = now.plus(12, ChronoUnit.HOURS);
Instant hoursBefore = now.minus(12, ChronoUnit.HOURS);
First, doing this kind of operations on java.time.LocalTime won't work! Or at least only if the time is "12:00:00" …
That is because you will have an over-/underflow when you add/substract 12 hours from any other time.
So your starting point should be to go for java.time.LocalDateTime (at least, although I would go for java.time.Instant). Now you can handle the over-/underflow, as you will get another day when adding or subtracting 12 hours.
How this works is shown in this anwswer: LocalDateTime allows nearly the same operations as Instant.

TimeDelta java?

I am trying to convert code from Python to Java. I need to rewrite the timedelta function in Java. Here is the code in Python:
def timeDate(date):
return (timedelta(seconds=date * 3600 % 86400))
Does anyone have any idea on how to make a function that acts the same?
double hours = 21.37865107050986;
long nanos = Math.round(hours * TimeUnit.HOURS.toNanos(1));
Duration d = Duration.ofNanos(nanos);
// Delete any whole days
d = d.minusDays(d.toDays());
System.out.println(d);
This prints:
PT21H22M43.143853836S
Which means: a duration of 21 hours 22 minutes 43.143853836 seconds.
Assumptions: I understand that you want a duration (the docs you link to say “A timedelta object represents a duration”). I have taken date to be a floating-point number of hours, and your modulo operation lead me to believe that you want the duration modulo 1 day (so 26 hours should come out as a duration of 2 hours).
The Duration class in Java is for durations, hence is the one that you should use. It doesn’t accept a floating point number for creation, so I converted your hours so nanoseconds and rounded to whole number. For the conversion I multiplied by the number of nanoseconds in 1 hour, which I got from the call to TimeUnit (this gives clearer and less error-prone code than multiplying out ourselves).
The code above will tacitly give incorrect results for numerically large numbers of hours, so you should check the range before using it. Up to 2 500 000 hours (100 000 days or nearly 300 years) you should be safe.
Please note: if date was a time of day and not a duration, it’s a completely different story. In this case you should use LocalTime in Java. It’s exactly for a time of day (without date and without time zone).
nanos = nanos % TimeUnit.DAYS.toNanos(1);
LocalTime timeOfDay = LocalTime.ofNanoOfDay(nanos);
System.out.println(timeOfDay);
21:22:43.143853836
Link: Documentation of the Duration class
As far as I know, Java doesn't have a built in DeltaTime function. However you can easily make your own.long startTime;
long delta; public void deltaTime(){ long currentTime = System.currentTimeMillis(); delta = currentTime - startTime;}
Whenever you want to start your DeltaTime timer, you just do time = System.currentTimeMillis;. This way, the variable "delta" is the amount of time between when you started the DeltaTime timer and when you end it using ClassNameHere.deltaTime();.
private static LocalTime timeDate(double d) {
//converts into a local time
return LocalTime.ofSecondOfDay((long)(d*3600%86400));
}
Input (d):
36.243356711275794
Output:
21:22:43

How to parse duration in format "HHmm" using JodaTime?

I'm trying to shift datetime by a Duration which I get in the format "HHmm", for example "0010" meaning 10 minutes.
I've found similar ticket (Parsing time strings like "1h 30min") but I can't make it work properly.
Here's the code:
PeriodFormatter hoursMinutes = new PeriodFormatterBuilder().appendHours().appendMinutes().toFormatter();
Duration duration = hoursMinutes.parsePeriod("0010").toStandardDuration();
duration.getStandardMinutes(); //Returns 600
For some reason, I get 600 minutes instead of 10. So it looks like the minutes were interpreted as hours, but I can't understand why. I've tried adding .maximumParsedDigits(2) for hours, but the result was the same.
Why is my code wrong? Is there some other way to initialize duration parser? Something, where I could just use the standard format like "HHmm"?
So the issue was really with the maximum parseddigits. I only had to add it before hours, not minutes. So the solution is this:
PeriodFormatter hoursMinutes =
new PeriodFormatterBuilder().maximumParsedDigits(2).appendHours().appendMinutes().toFormatter();
Duration duration = hoursMinutes.parsePeriod("0010").toStandardDuration();
duration.getStandardMinutes(); //Returns 10
According to the documentation:
getStandardMinutes
public long getStandardMinutes()
Gets the length of this duration in minutes assuming that there are the standard number of milliseconds in a minute. This method assumes that there are 60 seconds in a minute and 1000 milliseconds in a second. All currently supplied chronologies use this definition.
This returns getMillis() / 60000. The result is an integer division,
thus excess milliseconds are truncated.
Returns: the length of the duration in standard seconds
Seeing as 600 is actually 10 minutes in seconds (60 * 10), you got the answer you expected.

Get date representation in seconds?

I am using an API which requires a date parameter as a number of seconds, an int.
My problem is that I currently store this time in java.util.date and I was wondering if there is some way to convert the java.util.date variable to seconds so that I can fit it into the int parameter which the API requires?
import java.util.Date;
...
long secs = (new Date().getTime())/1000;
...
Please see - http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()
Since Java 8 and onwards there's this elegant method which returns the Epoch time in seconds (seconds since 0:00:0 January 1st 1970). You can then store this value as an numeric value: a "long" in this case.
long timestamp = java.time.Instant.now().getEpochSecond();
java.util.Date.getTime() it returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
java.util.Date date=new Date();   
System.out.println(date.getTime());
Output:
1340128712111
To get seconds from milliseconds you need to divide it by 1000.
long secs = date.getTime()/1000;
System.out.println(secs);
Output:
1340128712
Alternatively Instant.getEpochSecond() returns the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. Its available since Java v1.8 docs.
Number of seconds by itself doesn't mean much. Number of seconds within the current minute? Number of seconds since 0:00:00 Janurary 1st, 1970? Number of seconds since lunch? Could you be more specific.
Put it into the API also doesn't mean much, unless you specify exactly which API you are using, and where you are attempting to put these seconds.

Java: date & time relative to current (server) time

We're using MySQL to store some dates. I'm looking to show these as relative time periods in the user interface: 2 hours ago, 3 days ago etc. (Like Twitter does for the updates for example)
Is there a well-known way to accomplish this, or should I get creative with it?
Just to be clear, I want to transform:
07/26/2009 12:20 -> '2 days ago'
As I understand your problem, the "Human Time" class is a solution.
check Date Formatting and Parsing for Humans in Java with HumanTime
.
I would take a look at the Joda library for performing this type of date-time arithmetic. For example, you could create a Joda Duration and then convert it to a Period, giving you access to numerous useful methods:
ResultSet rs = ...
Date dbDate = rs.getDate("Date"); // Get stored time in database.
long serverTime = System.currentTimeMillis(); // Get current server time.
// Compute absolute difference between two time-stamps.
Duration duration = new Duration(Math.abs(serverTime - dbDate.getTime()));
// Convert to period and make use of getHours(), getMinutes(), etc for display purposes.
Period period = duration.toPeriod();
System.err.println("Hours: " + period.getHours());
System.err.println("Minutes: " + period.getMinutes()); // etc.
The Java standard API method for date calculations is Calendar.add() (which also takes negative parameters).
I think the most common solution is to convert it to unix timestamps (or equivalent, milliseconds in Java normally), take the difference and start dividing away.
time = now - then;
time /= 1000; /* if milliseconds... */
seconds = time % 60; time /= 60;
minutes = time % 60; time /= 60;
hours = time % 60; time /= 60;
days = time % 24; time /= 24;
weeks = time % 7; time /= 7;
or months (although, then it starts to get tricky...), or whatever you want to use.
Have fun.
My advice is run your server in UTC and then use JodaTime to do any date arithmetic or conversion between timezones.
There's considerably more to date arithmetic than meets the eye once you factor in things like DSL, leap-seconds, convention changes, etc and it's really the last thing you want to be doing yourself.
The question is rather vague.
In Java, using JodaTime Date API;
3 days ago:
DateTime date = new DateTime();
DateTime threeDA = date.plusDays(-3);
int daysBetween = Days.daysBetween(dbDate, threeDA).getDays();
int monthsBetween = Months.monthsBetween(dbDate, threeDA).getMonths();
or you could use the JodaTime Period/Duration objects.
In MySQL, use a built-in MySQL Date Function e.g.:
SELECT SUBTIME(SYSDATE(),'3'); -- untested, no MySQL to hand
SELECT SUBTIME('2007-12-31 23:59:59.999999','3 0:0:0.000000');
For date differences:
SELECT DATEDIFF(columnname, SYSDATE()); -- Days since
SELECT TIMEDIFF(columnname, SYSDATE()); -- Time since
In Java, using Gregorian Calendar:
GregorianCalendar threeDA = new GregorianCalendar();
threeDA.add(GregorianCalendar.DAY_OF_YEAR, -3);
If you can use java for the conversion, have a look at the Joda library.
On the MySQL side:
CONVERT('date-time-value-here', DATETIME) - NOW()

Categories

Resources