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));
}
}
Related
This question already has answers here:
Displaying the last two digits of the current year in Java
(7 answers)
Closed 5 years ago.
I am able to get Year in YYYY Format from my below Code. But I want in YY Format. Can anyone help?
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int hour = c.get(Calendar.HOUR_OF_DAY); // IF YOU USE HOUR IT WILL GIVE 12 HOUR USE HOUR_OF_DAY TO GET 24 HOUR FORMAT
int minutes = c.get(Calendar.MINUTE);
int date = c.get(Calendar.DATE);
int month = c.get(Calendar.MONTH) + 1; // in java month starts from 0 not from 1 so for december 11+1 = 12
int year = c.get(Calendar.YEAR);
yep :)
int year = c.get(Calendar.YEAR) % 100;
You could do:
int fourDigYear = c.get(Calendar.YEAR)
String yrStr = Integer.toString(digyear).substring(2);
int year = Integer.parseInt(yrStr);
for example if the Calendar year was the int 2014, "year" would come out as the integer 14. This ensures that any year put in it will ALWAYS export the numbers past "yy". So I guarantee you will have no problems with it until the year 10000.
EDIT:
To get this working for eternity, you can tweak it to this:
int digyear = c.get(Calendar.YEAR);
String yrStr = Integer.toString(digyear);
String yrStrEnd = yrStr.substring(yrStr.length() - 2);
int year = Integer.parseInt(yrStrEnd);
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:
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
How to calculate number of Tuesday in one month?
Using calender.set we can set particular month, after that how to calculate number of Mondays, Tuesdays etc. in that month?
Code is :
public static void main(String[] args )
{
Calendar calendar = Calendar.getInstance();
int month = calendar.MAY;
int year = 2012;
int date = 1 ;
calendar.set(year, month, date);
int MaxDay = calendar.getActualMaximum(calendar.DAY_OF_MONTH);
int mon=0;
for(int i = 1 ; i < MaxDay ; i++)
{
calendar.set(Calendar.DAY_OF_MONTH, i);
if (calendar.get(Calendar.DAY_OF_WEEK) == calendar.MONDAY )
mon++;
}
System.out.println("days : " + MaxDay);
System.out.println("MOndays :" + mon);
}
Without writing whole code here is the general idea:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MAY); // may is just an example
c.set(Calendar.YEAR, 2012);
int th = 0;
int maxDayInMonth = c.getMaximum(Calendar.MONTH);
for (int d = 1; d <= maxDayInMonth; d++) {
c.set(Calendar.DAY_OF_MONTH, d);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if (Calendar.THURSDAY == dayOfWeek) {
th++;
}
}
This code should count number of Thursday. I believe you can modify it to count number of all days of week.
Obviously this code is not efficient. It iterates over all the days in the month. You can optimize it by getting just get day of the week of the first day, the number of days in month and (I believe) you can write code that calculates number of each day of week without iterating over the whole month.
With Java 8+, you could write it in a more concise way:
public static int countDayOccurenceInMonth(DayOfWeek dow, YearMonth month) {
LocalDate start = month.atDay(1).with(TemporalAdjusters.nextOrSame(dow));
return (int) ChronoUnit.WEEKS.between(start, month.atEndOfMonth()) + 1;
}
Which you can call with:
int count = countDayOccurenceInMonth(DayOfWeek.TUESDAY, YearMonth.of(2012, 1));
System.out.println(count); //prints 5
AlexR mentioned the more efficient version. Thought I would give it a whirl:
private int getNumThursdays() {
// create instance of Gregorian calendar
Calendar gc = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
int currentWeekday = gc.get(Calendar.DAY_OF_WEEK);
// get number of days left in month
int daysLeft = gc.getActualMaximum(Calendar.DAY_OF_MONTH) -
gc.get(Calendar.DAY_OF_MONTH);
// move to closest thursday (either today or ahead)
while(currentWeekday != Calendar.THURSDAY) {
if (currentWeekday < 7) currentWeekday++;
else currentWeekday = 1;
daysLeft--;
}
// calculate the number of Thursdays left
return daysLeft / 7 + 1;
}
note: When getting the current year, month, day etc. it is dependent on your environment. For example if someone manually set the time on their phone to something wrong, then this calculation could be wrong. To ensure correctness, it is best to pull data about the current month, year, day, time from a trusted source.
Java calendar actually has a built in property for that Calendar.DAY_OF_WEEK_IN_MONTH
Calendar calendar = Calendar.getInstance(); //get instance
calendar.set(Calendar.DAY_OF_WEEK, 3); //make it be a Tuesday (crucial)
//optionally set the month you want here
calendar.set(Calendar.MONTH, 4) //May
calendar.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH); //for this month (what you want)
calendar.getMaximum(Calendar.DAY_OF_WEEK_IN_MONTH); //for any month (not so useful)
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);