This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 9 years ago.
hello I am trying to calculate how many days are left in a pregnancy term but I think my algorithm is incorrect
public int getDaysPregnantRemainder_new() {
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
long diffDays = 280 - ((getDueDate().getTime() - calendar.getTime()
.getTime()) / (24 * 60 * 60 * 1000));
return (int) Math.abs((diffDays) % 7);
}
I am basing it off of a 280 day term, getDueDate() is a Date object and getTime() returns millisecond unix time
On some real world days the number reported is off by one, sometimes, and I am starting to think my algorithm is just wrong, or the millisecond time get gradually further and further off, or the millisecond time is not precise enough, or the gregorian calendar function rounds weird.
All in all I'm not sure, any insight appreciated
I don't know about your algorithm, but this (is basically) the one I used while tracking my wife's pregency...nerds...
Save yourself a lot of "guess" work and get hold of Joda-Time
public class TestDueDate {
public static final int WEEKS_IN_PREGNANCY = 40;
public static final int DAYS_IN_PREGNANCY = WEEKS_IN_PREGNANCY * 7;
public static void main(String[] args) {
DateTime dueDate = new DateTime();
dueDate = dueDate.plusDays(DAYS_IN_PREGNANCY);
System.out.println("dueDate = " + dueDate);
DateTime today = DateTime.now();
Days d = Days.daysBetween(today, dueDate);
int daysRemaining = d.getDays();
int daysIn = DAYS_IN_PREGNANCY - daysRemaining;
int weekValue = daysIn / 7;
int weekPart = daysIn % 7;
String week = weekValue + "." + weekPart;
System.out.println("Days remaining = " + daysRemaining);
System.out.println("Days In = " + daysIn);
System.out.println("Week = " + week);
}
}
This will output...
dueDate = 2014-02-25T14:14:31.159+11:00
Days remaining = 279
Days In = 1
Week = 0.1
Related
I need to claculate the number of days between two dates without using any date or calendar classes provided by any library.
Here's my idea:
numberOfDays = Math.abs((toYear - fromYear) * 365);
numberOfDays = numberOfDays + Math.abs((toMonth - fromMonth) * 12);
numberOfDays = numberOfDays + Math.abs((toDay - fromDay));
Thoughts?
How many days between the start date and the end of the month?
How many days in each full month until the end of the year?
How many days in each full year until the year of the end date (counting leap years)?
How many days in each full month until the last month?
How many days from the start of the last month until the end date?
Some of these numbers may be zero.
In Java 8 you can do the following:
long days = ChronoUnit.DAYS.between(LocalDate.of(2014, Month.MARCH, 01), LocalDate.of(2014, Month.FEBRUARY, 15));
Would something like this do?
//get 2 random dates
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = new Date();
Date date2 = sdf.parse("2014-9-12");
final long msInADay = 24*60*60*1000; //turn a day to ms
//divide time difference by the ms of a day
int difference = (int)((date2.getTime() - date1.getTime()) / msInADay);
System.out.println(Math.abs(difference));//Math.abs so you can subtract dates in any order.
EDIT after updating your question:
You can do this:
static int calcDayDiff(int startY, int startM, int startD, int endY, int endM, int endD){
int result = (startY - endY) * 365;
result += (startM - endM) * 31;
result += (startD - endD);
return Math.abs(result);
}
Testing with: System.out.println(calcDayDiff(2014,9,13,2013,8,12)); will print 397
Note though that this is not a very good solution since not every month contains 31 days and not every year 365. You can fix the month day difference by adding some simple logic inside the method to not always multiply by 31. Since it's an assignment i guess you will be ok to consider every year having 365 days.
public class test {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2014, 8, 1, 0, 0, 0);
Date s = cal.getTime();
Date e = new Date();
System.out.println(days(s,e));
}
public static int days(Date start, Date end){
double aTms = Math.floor(start.getTime() - end.getTime());
return (int) (aTms/(24*60*+60*1000));
}
}
This question already has answers here:
Sum two dates in Java
(9 answers)
Closed 8 years ago.
I have two String times
1:30:00
1:35:00
Is there a simple way to add these two times and get a new time which should be something
3:05:00?
I want to do this at client side , so if i can avoid any date liabraries
String time1="0:01:30";
String time2="0:01:35";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
System.out.println("The sum is "+date3);
Ouput : The sum is 00:03:05
Keep in mind that you can convert int values for hours/minutes/seconds to a single int like this:
int totalSeconds = ((hours * 60) + minutes) * 60 + seconds;
And convert back:
int hours = totalSeconds / 3600; // Be sure to use integer arithmetic
int minutes = ((totalSeconds) / 60) % 60;
int seconds = totalSeconds % 60;
Or you can do arithmetic piecemeal as follows:
int totalHours = hours1 + hours2;
int totalMinutes = minutes1 + minutes2;
int totalSeconds = seconds1 + seconds2;
if (totalSeconds >= 60) {
totalMinutes ++;
totalSeconds = totalSeconds % 60;
}
if (totalMinutes >= 60) {
totalHours ++;
totalMinutes = totalMinutes % 60;
}
Use SimpleDateFormat to parse the Strings then you can add the hours minutes and seconds
something like
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
d1 = df.parse("1:30:00");
d2 = df.parse("1:35:00");
Long sumtime= d1.getTime()+d2.getTime();
you can see this here as well it looks like possible duplicate of #####
or if you want to use Calender API, then you can also do it using Calender API, then u can do something like
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Calendar cTotal = Calendar.getInstance();
cTotal.add(c1.get(Calendar.YEAR), c2.get(Calendar.YEAR));
cTotal.add(c1.get(Calendar.MONTH) + 1)), c2.get(Calendar.MONTH) + 1)); // Months are zero-based!
cTotal.add(c1.get(Calendar.DATE), c2.get(Calendar.DATE));
Just sum them as you sum numbers in 1st-2nd grades, going backwards through them.
Also make sure you move over digits to higher register when needed (i.e. not
always when reaching 10 but when reaching 24 or 60 for hours/minutes).
So I suggest you code this algorithm yourself.
I want to calculate the difference between a certain date and the current time.
int month = 9;
int day = 17;
int year = 2013;
Calendar date = new GregorianCalendar(year, month, day);
int miliseconds= (int) (System.currentTimeMillis() - calendar.getTimeInMillis());
System.out.println(msToString(second));
String msToString(int ms) {
return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format(new Date(ms));
}
the output is
13091-13091/? D/GTA: 1970-01-08 15:00:20.287
I want to get the amount of days, hours,minutes and seconds remaining.
What do I wrong?
you could try something like the following method
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TimeToGoCalculator {
/**
* #param args
*/
public static void main(String[] args) {
int month = 8;
int day = 19;
int year = 2013;
Calendar calendar = new GregorianCalendar(year, month, day);
int timeToGo = (int) (calendar.getTimeInMillis() - System.currentTimeMillis())/1000;
System.out.println(secondsToString(timeToGo));
}
private static String secondsToString(int seconds) {
int days = seconds / 24 / 3600;
int hours = (seconds - (days * 24 * 3600 )) / 3600;
int minutes = (seconds - (days * 24 * 3600 + hours * 3600)) / 60;
seconds = (seconds - (days * 24 * 3600 + hours * 3600 + minutes * 60));
return "The remaining time is "+days+" days, "+hours+" hours, "+minutes+
" minutes, and "+seconds+" seconds.";
}
}
That should give you the output you're looking for.
Notice that, when creating the GregorianCalendar object, the month is 0-indexed, so September would be = 8.
Use Joda Time library
Period class can help.
int month = 9;
int day = 17;
int year = 2013;
int hour= 0;
int minute =0;
int second =0;
int millisecond = 0;
DateTime dt1 = new DateTime(); //now
DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisecond);
//assuming dt1 is before dt2:
Period period = new Period(dt1, dt2, PeriodType.dayTime());
/*
periodType.dayTime()):
Gets a type that defines all standard fields from days downwards.
days
hours
minutes
seconds
milliseconds
*/
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendDays().appendSuffix("days ")
.appendHours().appendSuffix("hours ")
.appendMinutes().appendSuffix("minutes ")
.appendSeconds().appendSuffix("seconds ");
.toFormatter();
System.out.println(periodFormatter.print(period));
Are you able to use external libraries? Then Joda Time can help you, especially the Period class.
It has a constructor for two time instants and gives you the difference between the time instants in years/months/days/hours/seconds/milliseconds.
Your second variable holds an amount of milliseconds between the two dates, not a new date. You need to do some calculation using these milliseconds to get an amount of days, for instance.
You could do something like this:
int minutes = second/1000/60; // millis to seconds, seconds to minutes
to get an amount of minutes, then convert to hours, and so on.
This question already has answers here:
Find total hours between two Dates
(11 answers)
Closed 9 years ago.
I want to get how much date,hours,minutes and second remaining form Date1
String RemainingOn = "2013/25/1 22:36:24";
String mDate,mHour,mMinute,mSecond;
public String DateComparedateTime()
{
// compare RemainingOn with now
mDate = Difference date with RemainingOn and Now;
mHour = Difference hour with RemainingOn and Now;
mMinute = Difference minute with RemainingOn and Now;
mSecond = Difference second with RemainingOn and Now;
return mDate+","+mHour+","+mMinute+","+mSecond ;
}
following code gives idea
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
if you can use Joda Time
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
How do I convert a 7-digit julian date into a format like MM/dd/yyy?
Found a useful site: http://www.rgagnon.com/javadetails/java-0506.html
This should do the trick:
public static int[] fromJulian(double injulian) {
int jalpha,ja,jb,jc,jd,je,year,month,day;
double julian = julian + HALFSECOND / 86400.0;
ja = (int) julian;
if (ja>= JGREG) {
jalpha = (int) (((ja - 1867216) - 0.25) / 36524.25);
ja = ja + 1 + jalpha - jalpha / 4;
}
jb = ja + 1524;
jc = (int) (6680.0 + ((jb - 2439870) - 122.1) / 365.25);
jd = 365 * jc + jc / 4;
je = (int) ((jb - jd) / 30.6001);
day = jb - jd - (int) (30.6001 * je);
month = je - 1;
if (month > 12) month = month - 12;
year = jc - 4715;
if (month > 2) year--;
if (year <= 0) year--;
return new int[] {year, month, day};
}
Starting with Java 8, this becomes a one-liner to get the LocalDate:
LocalDate.MIN.with(JulianFields.JULIAN_DAY, julianDay)
.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
Where julianDay is your 7-digit number.
simple way is here and this will return approx 100% accurate information.
String getDobInfo(double doubleString){
SweDate sweDate = new SweDate(doubleString);
int year = sweDate.getYear();
int month = sweDate.getMonth();
int day = sweDate.getDay();
// getting hour,minute and sec from julian date
int hour = (int) Math.floor(sweDate.getHour());
int min = (int) Math
.round((sweDate.getHour() - Math.floor(hour)) * 60.0);
int sec = (int) (((sweDate.getHour() - Math.floor(hour)) * 60.0 - Math
.floor(min)) * 60.0);
return "DOB:(DD:MM:YY) "+day+":"+month+":"+year+" TOB:(HH:MM:SS) "+hour+":"+min+":"+sec;
}
download the Swiss Ephemeris library and enjoy coding!!!
Do you really mean a Julian date, like astronomers use? Ordinal dates, which are specified as a year (four digits) and the day within that year (3 digits), are sometimes incorrectly called Julian dates.
static String formatOrdinal(int year, int day) {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_YEAR, day);
Date date = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
return formatter.format(date);
}
This will give you the date at 00:00 local time; you may want to set the timezone on the calendars to GMT instead, depending on the application.
I see there are enough answers already provided. But any calendar related question is only half answered without mentioning joda-time ;-). Here is how simple it is with this library
// setup date object for the Battle of Hastings in 1066
Chronology chrono = JulianChronology.getInstance();
DateTime dt = new DateTime(1066, 10, 14, 10, 0, 0, 0, chrono);