Java - Convert Unix epoch time to date - java

I need to convert some epoch time stamps to the real date and have used some of the methods I found on stack overflow, but they give the wrong answer.
As an example, one date is "129732384262470907" in epoch time, which is "Mon, 20 Jan 6081 05:24:22 GMT" using http://www.epochconverter.com/
However, my code generates: "Wed Dec 24 14:54:05 CST 19179225"
String epochString = token.substring(0, comma);
long epoch = Long.parseLong(epochString);
Date logdate = new Date(epoch * 1000);
BufferedWriter timewrite = new BufferedWriter(new FileWriter(tempfile, true));
timewrite.write(logdate);
timewrite.flush();
timewrite.close();
The initial timestamp is in miliseconds, which in the examples I saw here I am supposed to multiply by 1000.
If I don't multiply by 1000, I get: "Mon Aug 08 01:14:30 CDT 4113025"
Both of which are wrong.
So where have I made my error?

129732384262470907 is actually in microseconds since the epoch if it's meant to be 6081, so you need to divide by 1000 if that's real input.
Note that epochconverter.com doesn't even handle that value - it only allows you to enter 129732384262470 which it then treats as milliseconds since the epoch.
You need to multiply by 1000 if your data is seconds since the epoch. Basically all you need to know is that Java expects milliseconds since the epoch; the rest should be plain sailing, assuming you know what your input data actually means.
If you could provide your real data, and what it's meant to represent, it's probably going to be easy to fix your problems.

If you look carefully, epochconverter.com truncated that number because it was too long for the entry field.
I suggest you print the current value of System.currentMillis() to see what approximate range a "current" epoch-based timestamp has, and re-scale your input number to match. I think you'll probably have to divide by 1000.
In fact, looking closer, if you divide by 10,000, you get 1297323842624, which comes out to a date in 2011. So it's not at all clear what units the number you've given are in.

Related

Convert 18 decimal Julian Timestamp with Java

I need to convert what I think is a Julian timestamp to a regular time stamp with Java.
The application that generates this timestamp is a proprietary payment system (Base24-EPS from ACI). I need to be able to pull and parse the value from the database with a Java application.
A sample timestamp value in decimal is 18 digits:
137955731472778910
With DALCI (internal tool provided by Base24-EPS), I can see this is equivalent of:
3: convert 137955731472778910 to datetime(yyyy/mm/dd hh:mm:ss);
2019/12/14 12:39:07
I found an answer here which seems to be related. But 137955731472778910 is smaller than 210866803200000000, which is the Julian timestamp for 01-JAN-1970 (epoch for unix time).
All the other Julian timestamp online converter I see, for example http://www.onlineconversion.com/julian_date.htm, have Julian date format as double 2458806.52903.
18 digits seem too long.
Do you know how can I parse this timestamp format with Java?
Many thanks.
Assuming you are in the UTC timezone (you probably aren't, but you haven't told me what timezone you are in), I have a formula:
long timestampFromAci = ...;
long timestampJava = (timestamp - 122192460002790000L) / 10000;
Instant.ofEpochMilli(timestampJava);
new Date(timestampJava); // Old, deprecated - use java.time classes
This assumes that the conversion is linear.
Your product timestamp has 10000 units per millisecond, since there are 2145052000 milliseconds between 2019/11/19 16:48:15 and 2019/12/14 12:39:07, and the difference in your product's timestamp is 21450514084700.
If you divide these two, that's almost exactly 10000 - the difference is because your tool doesn't display fractional seconds.
Extrapolating from that, I can derive that value that your product timestamp would have for the Unix epoch op 1/1/1970 - 122192460002790000.
However, as I said, I made the assumption that you are in the UTC timezone. For every hour that your timezone is off from UTC, you need to adjust that number by 3600 seconds times 10,000,000 units product timestamp units per second.

datestr function in MATLAB to Java

I have a number format in a file that Matlab converts to a date string. The format is structured, for example, as 732161.8561226851.
When I perform datestr(732161.8561226851) in Matlab, I get:
ans =
'02-Aug-2004 20:32:49'
I wish to achieve the same output but as a Java function. I haven't seen this format before, however, and am unsure of the conversion process taken.
What is the process to convert this into a date string so I can create a Java function?
// Matlab epoch is January 0, 0000, so subtract 1 day from January 1:
Instant matlabEpoch = Instant.parse("0000-01-01T00:00:00Z").minus(1, ChronoUnit.DAYS);
Instant inst = matlabEpoch.plusMillis(
Math.round(732161.8561226851 * TimeUnit.DAYS.toMillis(1)));
System.out.println(inst);
This prints:
2004-08-02T20:32:49Z
I trust that #Riley Jacob’s answer is correct and see that it uses the long outdated Date class. So I wanted to give a modern version of the same answer. Other than avoiding the old-fashioned class it also has the advantage of leaving most of the calculation to library methods, which in turn gives clearer code.
I find it worth noting that we hit the same result as Matlab with millisecond precision. If the result had been one millisecond off, it would have been printed as either 2004-08-02T20:32:48.999Z or 2004-08-02T20:32:49.001Z.
Link: Oracle tutorial: Date Time explaining how to use java.time.
The format is MATLAB's DateNumber: the number of days elasped since January 0, 0000. You can use Java's toUTCString with some modifying:
var d = new Date(dateMATLAB*86400000-62167305600000);
var n = d.toUTCString();
Where dateMATLAB is MATLAB's date output. The value 62167305600000 is the number of milliseconds which elapsed between year 0 and 1970. Using your example,
var d = new Date(732161.8561226851*86400000-62167305600000);
var n = d.toUTCString();
Will output
Mon, 02 Aug 2004 20:32:48 GMT

Find out the difference between two dates represented by two Long epoch values

My need is that I have a value in Long, which represent the milliseconds value since epoch. I wish to find out the difference in the number of days between that day and the current day.
I am using Java8's DAYS.between(inputDate, currentDate)
For the currentDate I have used LocalDateTime currentDate = LocalDateTime.now();
But the issue I am facing is when I am converting the long value into java8 LocalDateTime. When I use
LocalDate date = Instant.ofEpochMilli(1490372528)
.atZone(ZoneId.systemDefault())
.toLocalDate();
The result is 1970-01-18 while when I enter the same value in https://www.epochconverter.com/ it gives Fri, 24 Mar 2017 16:22:08 GMT
Why is this discrepancy there? How to effectively get a java8 date from a long value to use in DAYS.between()?
You have to decide. Either, your number is “milliseconds value since epoch”, as you stated in your question, or it is “number of seconds that have elapsed since January 1, 1970”, as stated (and used) on the linked web site.
If it is truly “milliseconds since epoch”, you can use
System.out.println(Instant.ofEpochMilli(1490372528).until(Instant.now(), ChronoUnit.DAYS));
to print the number of days, which is, by the way, not simpler than the pre-Java 8 code
System.out.println(TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis()-1490372528));
If your number actually is “seconds since epoch”, you have little to change in your code
System.out.println(Instant.ofEpochSecond(1490372528).until(Instant.now(),ChronoUnit.DAYS));
which is equivalent to
System.out.println(ChronoUnit.DAYS.between(Instant.ofEpochSecond(1490372528),Instant.now()));
as you mentioned DAYS.between explicitly. It will just delegate to the until method used above. The equivalent pre-Java 8 code would be slightly more complicated
System.out.println(TimeUnit.MILLISECONDS.toDays(
System.currentTimeMillis()-TimeUnit.SECONDS.toMillis(1490372528)));

Getting Timezone Information from Long value in java

Can we get from which timezone the Long Value is produced?
I have long values of Date. I want to know from which timezone it is generated.
For e.g
Long value: 1435640400000
Date: 30 June 2015 CDT
I want to develop program which input will be the Date in long value
that will return output as Timezone with the respective
long value for 30 June 2015 12:00 AM GMT/UTC
The unix time (as it is called) is not a date. You can calculate a date from it but it really is just the duration of seconds (or ms) since 01/01/1970 at 00:00 UTC.
This means it has no timezone attached to it. You need the "target" timezone to calculate the actual date from it, but simply having this number does not include any timezone information (which means you'll need to get it somewhere else in order to calculate dates).
Think of the unix timestamp more as a duration than a date. It's like saying "I'll meet you in 30 minutes". Those 30 minutes do not have a timezone attached to them. To you and the person you're talking to, that meeting might happen at different dates (e.g. 2:30pm vs. 3:30pm) because of timezones. But it will still happen at the same point in time relative to the moment you said it.
I hope this makes the difference somewhat clearer.
There was a way to do this directly via the getTimezoneOffset() function in the Date class but that has been deprecated.
It has been replaced by
(Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)

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.

Categories

Resources