I am implementing a routine to convert from Epoch timestamp into year, month, day, hours, minutes and seconds.
Important note: I can not use any of the existing Java libraries because this routine is used as a test program to be later implemented in a GPU. Therefore please do not suggest to use Localdate, ZonedDateTime, Datetime, etc. The routine must use plain data types and basic arithmetic operations.
These are the specs:
The input data is a UNIX Epoch timestamp in seconds.
The output data is a string with the year/month/day hour:minute.
The date times are constrained from January 1st 1990 to January 1st 2050.
No leap seconds as input data are UNIX Epoch timestamps.
Only valid epoch timestamps based on these conditions are handled by the routine.
This is what I have tried, which I include as a replicable Java program.
I have a valid routine which works for dates above January 1st 2000: routine epochToDatetimeBase2000.
I am trying to code a module which will work for dates above January 1st 1990, routine epochToDatetimeBase1990, which does not work.
This is the complete replicable source code of the program including both routines and the test data:
public class MyClass {
public static String epochToDatetimeBase2000(int epoch) {
int epochOriginal = epoch;
epoch = epoch - 946684800; // 946684800 is Epoch for Saturday, 1 January 2000 00:00:00
int[] days = new int[]{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335,
366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700,
731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065,
1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
};
int second = epoch % 60;
epoch = epoch / 60;
int minute = epoch % 60;
epoch = epoch / 60;
int hour = epoch % 24;
epoch = epoch / 24;
int years = epoch/(365*4+1)*4;
epoch %= 365*4+1;
int year;
for (year=3; year>0; year=year-1)
{
if (epoch >= days[year*12])
break;
}
int month;
for (month=11; month>0; month--)
{
if (epoch >= days[year*12 + month])
break;
}
int yearVal = years+year;
int monthVal = month+1;
int dayVal = epoch-days[year*12 + month]+1;
String strDatetime = String.format("%d %02d/%02d/%02d %02d:%02d.%02d", epochOriginal, dayVal, monthVal, 2000+yearVal, hour, minute, second); // Float value.
return strDatetime;
}
public static String epochToDatetimeBase1990(int epoch) {
int epochOriginal = epoch;
epoch = epoch - 631152000; // 631152000 is Epoch for Monday, 1 January 1990 00:00:00
int[] days = new int[]{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335,
366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700,
731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065,
1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
};
int second = epoch % 60;
epoch = epoch / 60;
int minute = epoch % 60;
epoch = epoch / 60;
int hour = epoch % 24;
epoch = epoch / 24;
int years = epoch/(365*4+1)*4;
epoch %= 365*4+1;
int year;
for (year=3; year>0; year=year-1)
{
if (epoch >= days[year*12])
break;
}
int month;
for (month=11; month>0; month--)
{
if (epoch >= days[year*12 + month])
break;
}
int yearVal = years+year;
int monthVal = month+1;
int dayVal = epoch-days[year*12 + month]+1;
String strDatetime = String.format("%d %02d/%02d/%02d %02d:%02d.%02d", epochOriginal, dayVal, monthVal, 1990+yearVal, hour, minute, second); // Float value.
return strDatetime;
}
public static void main(String args[]) {
// USING BASE 2000
System.out.println(epochToDatetimeBase2000(978307200)); // Epoch timestamp: 978307200 Date and time (GMT): Monday, 1 January 2001 00:00:00
System.out.println(epochToDatetimeBase2000(631152000)); // Epoch timestamp: 631152000 Date and time (GMT): Tuesday, 1 January 1990 00:00:00
System.out.println(epochToDatetimeBase2000(662688000)); // Epoch timestamp: 662688000 Date and time (GMT): Tuesday, 1 January 1991 00:00:00
// USING BASE 1990
System.out.println(epochToDatetimeBase1990(978307200)); // Epoch timestamp: 978307200 Date and time (GMT): Monday, 1 January 2001 00:00:00
System.out.println(epochToDatetimeBase1990(631152000)); // Epoch timestamp: 631152000 Date and time (GMT): Tuesday, 1 January 1990 00:00:00
System.out.println(epochToDatetimeBase1990(662688000)); // Epoch timestamp: 662688000 Date and time (GMT): Tuesday, 1 January 1991 00:00:00
}
}
This is the output:
978307200 01/01/2001 00:00.00
631152000 -729/01/1992 00:00.00
662688000 -364/01/1992 00:00.00
978307200 01/01/2001 00:00.00
631152000 01/01/1990 00:00.00
662688000 31/12/1990 00:00.00 <- SHALL BE 1 January 1991 00:00:00
Could there be a mistake in your days array for epochToDatetimeBase1990? I notice the values are exactly the same as in epochToDatetimeBase2000. 2000 is leap year but 1990 isn't! So the leap years begin in different places in the array. I think days should defined like be this in epochToDatetimeBase1990:
int[] days = new int[]{
// 1990 is NOT a leap year
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
365, 396, 424, 455, 485, 516, 546, 577, 608, 638, 669, 699,
// 1992 is a leap year here
730, 761, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065,
1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
};
I have prepared another solution. Please have a look.
Also this is helpful for any other boundary of years, for that just change START_YEAR, START_EPOCH and END_YEAR.
final static int START_YEAR = 1990;
final static long START_EPOCH = 631152000;
final static int END_YEAR = 2050;
final static int[] MONTH_DAYS = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
private static void convertEpochToDateTime(long epoch){
long relativeEpoch = epoch-START_EPOCH;
int[] daysAndRemainingSeconds = getTotalDaysAndRemainingSeconds(relativeEpoch);
int remainingSeconds = daysAndRemainingSeconds[1];
int[] time = convertSecondsToTime(remainingSeconds);
int totalDays = daysAndRemainingSeconds[0];
int[] yearAndRemainingDays = getYearAndRemainingDays(totalDays);
int year = yearAndRemainingDays[0];
int remainingDays = yearAndRemainingDays[1];
int[] monthAndDays =getMonthsAndRemaingDays(remainingDays,isLeapYear(year));
String strDatetime = String.format("%d %02d/%02d/%02d %02d:%02d.%02d", epoch, monthAndDays[1]+1, monthAndDays[0], year, time[0], time[1], time[2]);
System.out.println(String.valueOf(strDatetime));
}
private static int[] getTotalDaysAndRemainingSeconds(long seconds){
return new int[]{(int)seconds/86400,(int)seconds%86400};
}
private static int[] getYearAndRemainingDays(int days){
int tmpDays = 0;
for(int year=START_YEAR;year<=END_YEAR;year++){
int daysInYear = isLeapYear(year)?366:365;
if(tmpDays+daysInYear>days) return new int[]{year,days-tmpDays};
tmpDays +=daysInYear;
}
return new int[]{0,0};
}
private static boolean isLeapYear(int year){
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
private static int[] convertSecondsToTime(int seconds){
int sec = seconds % 60;
int hr = seconds / 60;
int min = hr % 60;
hr = hr / 60;
return new int[]{hr,min,sec};
}
private static int[] getMonthsAndRemaingDays(int days,boolean leapYear){
int tmdDays = 0;
for(int month=1;month<=12;month++){
int daysInThisMonth = MONTH_DAYS[month-1]+(month==2 && leapYear?1:0);
if(tmdDays+daysInThisMonth>days) return new int[]{month,days-tmdDays};
tmdDays+=daysInThisMonth;
}
return new int[]{12,0};
}
How can I convert 0.230324074074074 to 05:31:40 in Java? I have code in sql but need in java.
(select * from(SELECT TRUNC (
( (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
* 24
* 60)
/ 60)
|| ':'
|| ( ( (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
* 24
* 60)
- TRUNC (
( ( X_GSA_LEAVE_SITE
- X_GSA_ARRIVE_ONSITE)
* 24
* 60)
/ 60)
* 60)
It appears that the value 0.230324 is a fraction of a day, and you want to display this as hours:minutes:seconds. There is a fairly straightforward way to do this in Java 8:
double input = 0.230324074074074d;
long seconds = new Double(input*24*60*60).longValue();
System.out.println(LocalTime.MIN.plusSeconds(seconds)
.format(DateTimeFormatter.ISO_LOCAL_TIME));
05:31:39
Demo
You can convert that fraction of day to a LocalTime using:
LocalTime.ofSecondOfDay((long)(0.230324074074074 * 24 * 60 * 60))
This converts the value to seconds and constructs a LocalTime object. Printing the result outputs "05:31:39" (LocalTime.toString outputs time in your desired format). You may need to control rounding in a different way if you expect exactly 05:31:40)
Just for fun here is an old fashioned Calendar version
int seconds = (int) (0.230324074074074 * 24 * 60 * 60);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.SECOND, seconds);
String result = String.format("%02d:%02d:%02d",
cal.get(Calendar.HOUR),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND));
System.out.println(result);
long seconds = (long) (0.230324074074074 * 24 * 60 * 60);
String result = String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
System.out.println(result);
Hi i am trying to calculate difference of two dates in days. The dates are 14 of this month and today. It should be 2. But o/p is 0 always.
Code:
long today = (new java.util.Date().getTime());
long difference =(long) (today - 1394809789186.0);
long daysdifference = difference/(24*3600*1000);
System.out.println(daysdifference);
o/p:
0.
whats wrong?
Now i did another trick and it gives perfect answer dont know whats wrong with above code...
SimpleDateFormat df = new SimpleDateFormat("dd.mm.yyyy");
long firstdateseconds = df.parse("14.03.2014").getTime();
long today = df.parse("16.03.2014").getTime();
long difference = (today-firstdateseconds);
long days = (long)(difference/(24*3600*1000));
System.out.println(days);
o/p : 2 // now correct bingo!
Guys whats happening?
I used the following simple code to accomplish what you want:
import java.util.Date;
public class datediff {
public static void main(String[] args) {
Date d1 = new Date();
Date d2 = new Date(2014 - 1900, 2, 14);
long d1_millis = d1.getTime();
long d2_millis = d2.getTime();
long diffMillis = d1_millis - d2_millis;
long diffDays = diffMillis / (24 * 3600 * 1000);
System.out.println("Difference in days: " + diffDays);
}
}
OUTPUT:
Difference in days: 2
Also note that the magic number that you are using while calculating the difference is incorrect.
The actual value to subtract is : 1394735400000
That is the most dangerous disadvantage of using magic numbers.
Hope that clarifies things for you.
Perhaps a combined TimeZone and "Time (hours/minutes/seconds)" issue?
Case I
Different timezones and different day times:
public static void main(final String[] args) {
final Calendar march14 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march14.set(2014, Calendar.MARCH, 14, 23, 59, 0);
final Calendar march16 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
march16.set(2014, Calendar.MARCH, 16, 0, 0, 0);
final long diffInMs = march16.getTimeInMillis() - march14.getTimeInMillis();
System.out.println("diff = " + diffInMs / (24 * 3600 * 1000)+" day(s)");
}
This prints:
diff = 0 day(s)
Case II
However, adjusting the time zone:
public static void main(final String[] args) {
final Calendar march14 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march14.set(2014, Calendar.MARCH, 14, 23, 59, 0);
final Calendar march16 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii")); // <- CHANGE!
march16.set(2014, Calendar.MARCH, 16, 0, 0, 0);
final long diffInMs = march16.getTimeInMillis() - march14.getTimeInMillis();
System.out.println("diff = " + diffInMs / (24 * 3600 * 1000)+" day(s)");
}
This prints:
diff = 1 day(s)
Case III
And adjusting the time (hours/minutes/seconds):
public static void main(final String[] args) {
final Calendar march14 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march14.set(2014, Calendar.MARCH, 14, 0, 0, 0); // <- CHANGE!
final Calendar march16 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march16.set(2014, Calendar.MARCH, 16, 0, 0, 0);
final long diffInMs = march16.getTimeInMillis() - march14.getTimeInMillis();
System.out.println("diff = " + diffInMs / (24 * 3600 * 1000)+" day(s)");
}
This prints:
diff = 2 day(s)
Conclusions
My two advices:
Don't use magic numbers, set all parts of your date/calendar objects that are relevant
Always set the TimeZone when working with date/time
Additional note to SimpleDateFormat
By the way: In SimpleDateFormat m is for minutes, M for month in year, see http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. It was pure random that the result of your calculations was 2.
Use double you are crossing a truncation issue