Days difference in dates in java giving wrong output - java

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

Related

How do I implement a routine to convert epoch timestamp without using any library/package?

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};
}

Convert Days to hours:minutes:second java

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);

getTimeinMillis returns a negative value

I am making an app which can show time left to some date, and an elapsed time after some date. But I endure some difficulties with dates less than 1970 and bigger than 3300. I have found an explanation why it happens.
The problem is this sentence from getTimeInMillis:
the current time as UTC milliseconds from the epoch.
And, as far as i remember, the epoch started on January 1st 1970 you get a negative number for anything before that.
My question is how to solve this problem. (And yes i have heard about JodaTime, I am not allowed to use this library in this app.)
What default(standard) tools should i use?
Here it is a piece of code that does not work properly.
private void getDateTime()
{
Date date = new Date();
timeRemaining = Calendar.getInstance();
date.setTime(timeRemaining.getTimeInMillis());
millis = Math.abs(timeRemaining.getTimeInMillis() - targetDate.getTimeInMillis());
int scnds = (int) (millis / 1000) % 60 ;
int mnts = (int) ((millis / (1000 * 60)) % 60);
int hrs = (int) ((millis / (1000 * 60 * 60)) % 24);
int dys = (int) (millis / (1000 * 60 * 60 * 24));
resultDate.setText(getString(R.string.formating, dys, hrs, mnts, scnds));
}
You can achieve this by leveraging the Duration and LocalDateTime class(es) introduced in Java 8 --
import java.time.Duration;
import java.time.LocalDateTime;
class Main {
public static void main(String[] args) {
LocalDateTime fromDateTime = LocalDateTime.of(1914, 9, 10, 0, 0, 0);
LocalDateTime toDateTime = LocalDateTime.of(2014, 12, 16, 0, 0, 0);
System.out.println(Duration.between(fromDateTime, toDateTime).toMillis());
}
}

Calculations of the path of the Sun

I'm writing several methods necessary to calculate the path of the Sun across a specific point. I have written the code using two different sources for my calculations and neither is producing the desired result. The sources are: http://www.pveducation.org/pvcdrom/properties-of-sunlight/suns-position and
http://www.esrl.noaa.gov/gmd/grad/solcalc/solareqns.PDF
Note: Degrees to arcminutes is Deg * 60 min.
localSolartime: I have converted the longitude to 'minutes', the local standard time meridian(lstm) derived from the localStandardTimeMeridian method returns a value that is in 'minutes', and the equationOfTime which is also returned in 'minutes'. Using the equation from pveducation, I've calculated the time correction which accounts for the small time variations within a given time zone. When I apply this result and the localTime, each in minutes, to the local solar time (lst) equation, the result is 676.515 (at this moment), which does not make any sense to me. The local solar time, as I understand it, represents the time with respect to the Sun and when it is at its highest point in the sky, locally, is considered solar noon. 676.515 does not make sense. Does anybody understand what might be causing this.
HourAngle: I'm hoping that once I fix the localSolarTime method, this will not need to be corrected.
I've chosen Washington DC for the latitude and longitude. Both the Zenith and Azimuth readings should be positive values, and for my region at this moment, are 66 and 201 respectively.
public class PathOfSun {
static LocalTime localTime = LocalTime.now();
static double dcLat = 38.83;
static double dcLong = -77.02;
static DecimalFormat df = new DecimalFormat("#.0");
public static void main(String [] args) {
int day = dayOfYear();
double equationOfTime = equationOfTime(day);
double lstm = localTimeMeridian();
double lst = localSolarTime(equationOfTime, dcLong, lstm);
double declination = declination(day);
double hourAngle = hourAngle(lst);
double zenith = zenith(dcLat, declination, hourAngle);
double azimuth = azimuth(dcLong, declination, zenith, hourAngle);
}
//Longitude of timezone meridian
public static double localTimeMeridian() {
TimeZone gmt = TimeZone.getTimeZone("GMT");
TimeZone est = TimeZone.getTimeZone("EST");
int td = gmt.getRawOffset() - est.getRawOffset();
double localStandardTimeMeridian = 15 * (td/(1000*60*60)); //convert td to hours
//System.out.println("Local Time Meridian: " + localStandardTimeMeridian);
return localStandardTimeMeridian;
}
//Get the number of days since Jan. 1
public static int dayOfYear() {
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
int dayOfYear = localCalendar.get(Calendar.DAY_OF_YEAR);
//System.out.println("Day: " + dayOfYear);
return dayOfYear;
}
//Emperical equation to correct the eccentricity of Earth's orbit and axial tilt
public static double equationOfTime (double day) {
double d =(360.0/365.0)*(day - 81);
d = Math.toRadians(d);
double equationTime = 9.87*sin(2*d)-7.53*cos(d)-1.54*sin(d);
//System.out.println("Equation Of Time: " + equationTime);
return equationTime;
}
//The angle between the equator and a line drawn from the center of the Sun(degrees)
public static double declination(int dayOfYear) {
double declination = 23.5*sin((Math.toRadians(360.0/365.0))*(dayOfYear - 81));
//System.out.println("Declination: " + df.format(declination));
return declination;
}
//Add the number of minutes past midnight localtime//
public static double hourAngle(double localSolarTime) {
double hourAngle = 15 * (localSolarTime - 13);
System.out.println("Hour Angle: " + df.format(hourAngle)); //(degrees)
return hourAngle;
}
//Account for the variation within timezone - increases accuracy
public static double localSolarTime(double equationOfTime, double longitude, double lstm) {
//LocalSolarTime = 4min * (longitude + localStandardTimeMeridian) + equationOfTime
//Time Correction is time variation within given time zone (minutes)
//longitude = longitude/60; //convert degrees to arcminutes
double localStandardTimeMeridian = lstm;
double timeCorrection = (4 * (longitude + localStandardTimeMeridian) + equationOfTime);
System.out.println("Time Correction: " + timeCorrection); //(in minutes)
//localSolarTime represents solar time where noon represents sun's is highest position
// in sky and the hour angle is 0 -- hour angle is negative in morning, and positive after solar noon.
double localSolarTime = (localTime.toSecondOfDay() + (timeCorrection*60)); //(seconds)
localSolarTime = localSolarTime/(60*60); //convert from seconds to hours
//Convert double to Time (HH:mm:ss) for console output
int hours = (int) Math.floor(localSolarTime);
int minutes = (int) ((localSolarTime - hours) * 60);
//-1 for the daylight savings
Time solarTime = new Time((hours-1), minutes, 0);
System.out.println("Local Solar Time: " + solarTime); //hours
return localSolarTime;
}
public static double azimuth(double lat, double declination, double zenith, double hourAngle) {
double azimuthDegree = 0;
double elevation = 90 - zenith;
elevation = Math.toRadians(elevation);
zenith = Math.toRadians(zenith);
lat = Math.toRadians(lat);
declination = Math.toRadians(declination);
hourAngle = Math.round(hourAngle);
hourAngle = Math.toRadians(hourAngle);
//double azimuthRadian = -sin(hourAngle)*cos(declination) / cos(elevation);
double azimuthRadian = ((sin(declination)*cos(lat)) - (cos(hourAngle)*cos(declination)*
sin(lat)))/cos(elevation);
//Account for time quadrants
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour > 0 && hour < 6) {
azimuthDegree = Math.toDegrees(acos(azimuthRadian));
}
else if(hour >= 6 && hour < 12) {
azimuthDegree = Math.toDegrees(acos(azimuthRadian));
azimuthDegree = 180 - azimuthDegree;
} else if (hour >= 12 && hour < 18) {
azimuthDegree = Math.toDegrees(acos(azimuthRadian));
azimuthDegree = azimuthDegree - 180;
} else if (hour >= 18 && hour < 24) {
azimuthDegree = Math.toDegrees(acos(azimuthRadian));
azimuthDegree = 360 - azimuthDegree;
}
System.out.println("Azimuth: " + df.format(azimuthDegree));
return azimuthDegree;
}
public static double zenith(double lat, double declination, double hourAngle) {
lat = Math.toRadians(lat);
declination = Math.toRadians(declination);
hourAngle = Math.round(hourAngle);
hourAngle = Math.toRadians(hourAngle);
//Solar Zenith Angle
double zenith = Math.toDegrees(acos(sin(lat)*sin(declination) + (cos(lat)*cos(declination)*cos(hourAngle))));
//Solar Elevation Angle
double elevation = Math.toDegrees(asin(sin(lat)*sin(declination) + (cos(lat)*cos(declination)*cos(hourAngle))));
System.out.println("Elevation: " + df.format(elevation));
System.out.println("Zenith: " + df.format(zenith));
return zenith;
}
}
Just to reiterate, the day, local time meridian are exactly correct, and the equation of time and declination are accurate but not exact.
----UPDATE OUTPUT----
-----UPDATE-----
Used the scatterchart to display the sun's elevation/azimuth throughout day. I am still having trouble figuring out the azimuth output. It is correct for long time, but then it will change from increasing and start to decrease (~270-->0). I will be sure to update the code once I finally get the output right.
You pass the longitude to localSolarTime() as degrees, and then you divide that by 60, with a comment claiming this is in order to convert to minutes of arc. This is wrong; your later calculations require degrees, and even if you needed minutes of arc, you'd multiply by 60, not divide.
This mistaken division results in a longitude of -1.3°, and when you find the angle between your local time meridian and your position, you get a large angle (about 75°). It should be a small angle, generally ±7.5°. The large angle results in a large time correction, and throws everything off.
Update: In the updated version of the azimuth() method, the quadrant selection should be based on the hour angle of the sun, or, equivalently, on local solar time, rather than standard wall clock time. And, the hour angle used in all calculations should not be rounded. Rather than testing four different quadrants, the method could look like this:
public static double azimuth(double lat, double declination, double zenith, double hourAngle)
{
double elevation = Math.toRadians(90 - zenith);
lat = Math.toRadians(lat);
declination = Math.toRadians(declination);
hourAngle = Math.toRadians(hourAngle);
double azimuthRadian = acos(((sin(declination) * cos(lat)) - (cos(hourAngle) * cos(declination) * sin(lat))) / cos(elevation));
double azimuthDegree = Math.toDegrees(azimuthRadian);
if (hourAngle > 0)
azimuthDegree = 360 - azimuthDegree;
System.out.println("Azimuth: " + df.format(azimuthDegree));
return azimuthDegree;
}
Finally, you are passing dcLong in as the lat parameter of the azimuth() method; this should be dcLat.
I'd recommend using radians internally throughout, and only converting from and to degrees on input and output. This will help prevent mistakes, and cut down on rounding errors and unnecessary clutter.

How timer scheduler run every 15 minutes interval hourly basis

Hi, I would like to run method interval of every 15 minutes .
Example: If my application initial server start time example 0:12 it
won't be call timer scheduler run method.
so my timer scheduler run method particular interval of every
hourly 15 minutes like :
0:15,0:30,0:45,1:00,1:15,1:30,1:45,2:00,2:15,2:30,2:45,.....etc.
Below sample snippet code always run method executed when initial
application start please let me know where I have made mistaken?
As per my requirement I need to implement in Timer-Task Scheduler.
private class TimerExample{
private static Timer timer = new Timer();
private static Calendar getFirstTime() {
Calendar cal = Calendar.getInstance();
int currentMinute = cal.get(Calendar.MINUTE);
if (currentMinute < 45) {
cal.set(Calendar.MINUTE, 45);
}
if (currentMinute < 30) {
cal.set(Calendar.MINUTE, 30);
}
if (currentMinute < 15) {
cal.set(Calendar.MINUTE, 15);
}
if (currentMinute >= 45) {
cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) + 1);
cal.set(Calendar.MINUTE, 0);
}
cal.set(Calendar.SECOND, 0);
return cal;
}
public static void main(String... args) {
Calendar firstTaskTime = getFirstTime();
System.out.println("Task will start at: " + firstTaskTime.getTime());
timer.schedule(new MyTask(), firstTaskTime.getTime(), 1000 * 60 * 15);
}
}

Categories