How to get current Century from a date in Java?
For example the date "06/03/2011" according to format "MM/dd/yyyy". How can I get current century from this date using SimpleDateFormat?
Date date = new SimpleDateFormat("MM/dd/yyyy").parse(yourString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int century = (calendar.get(Calendar.YEAR) / 100) +1;
A slight change to what Harry Lime posted. His logic is not entirely correct. Year 1901 would be 20th century, but 1900 would be 19th century.
public class CenturyYear {
public static void main(String[] args) {
int test = centuryFromYear(1900);
System.out.println(test);
}
static int centuryFromYear(int year) {
if (year % 100 == 0) {
year = year / 100;
} else {
year = (year / 100) + 1;
}
return year;
}
}
The other Answers are correct but outdated.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
To parse specify a formatting pattern. By the way, I suggest using ISO 8601 standard formats which can be parsed directly by java.time classes.
String input = "06/03/2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MM/dd/uuuu" ).withLocale ( Locale.US );
LocalDate ld = LocalDate.parse ( input , f );
To get the century, just take the year number and divide by 100. If you want the ordinal number, "twenty-first century" for 20xx, add one.
int centuryPart = ( ld.getYear () / 100 );
int centuryOrdinal = ( ( ld.getYear () / 100 ) + 1 );
Dump to console.
System.out.println ( "input: " + input + " | ld: " + ld + " | centuryPart: " + centuryPart + " | centuryOrdinal: " + centuryOrdinal );
input: 06/03/2011 | ld: 2011-06-03 | centuryPart: 20 | centuryOrdinal: 21
int century = (year + 99)/ 100;
I dont know anything about Java but why don't you just get the full year and make the last 2 digits 0?
EDIT
If you want 2011 to become 21st century - just get the fully qualified year in string format, then knock off the last 2 characters, then parse to an int and add 1!
You would simply return (year + 99) / 100
Split it by the slahes, get the first two symbols of the third element in the resulting array, Integer.parseInt it and add 1, that is:
String arr = myDate.split("/");
String shortYear = myDate[2].substring(0, 2);
int century = Integer.parseInt(shortYear) + 1;
(not sure about the substring() syntax off the top of my head)
Related
[purpose]
How to get int value after dividing 2 values(long-type).
[problem]
I changed the time(todaySeatedEndDateStr's HH:mm:ss part), but it is impossible to obtain an accurate value.
And I'm not sure that value is correct.
The main formula>
c'' = b / (a+b) * c
a, b : long type
c : int type
c'' : int type
Finally I want to get C''
Situation pic
# Test Code
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeCalculateTest {
public static void main(String[] args) throws Exception {
//2016-09-20 00:00:00 (Today's start point)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String todayStartDateStr = "2016-09-20 00:00:00";
Date todayStartDate = sdf.parse(todayStartDateStr);
//2016-09-19 23:30:00 (Yesterday's particular point)
String yesterdaySeatedStartDateStr = "2016-09-19 23:30:00";
Date yesterdaySeatedStartDate = sdf.parse(yesterdaySeatedStartDateStr);
//2016-09-20 03:30:00 (Today's particular point)
String todaySeatedEndDateStr = "2016-09-20 21:30:00";
Date todaySeatedEndDate = sdf.parse(todaySeatedEndDateStr);
System.out.println("Today's Start Date String : " + todayStartDateStr);
System.out.println("Today's Start Date Long: " + todayStartDate.getTime());
System.out.println("Yesterday's Start Date String : " + yesterdaySeatedStartDateStr);
System.out.println("Yesterday Start Date Long : " + yesterdaySeatedStartDate.getTime());
System.out.println("Today's End Date String : " + todaySeatedEndDateStr);
System.out.println("Today's End Date Long : " + todaySeatedEndDate.getTime());
int c = 500; // <------ c
System.out.println("c: " + c);
if (yesterdaySeatedStartDate.compareTo(todayStartDate) < 0) {
long a = yesterdaySeatedStartDate.getTime(); // <----- a
long b = todaySeatedEndDate.getTime(); // <------ b
long abSum = a + b; // <------ a+b
System.out.println("Yesterday's long value : " + a);
System.out.println("Today's long value : " + b);
System.out.println("---> Sum : " + abSum);
long result = (long) ((float)b / (float)abSum * c);
System.out.println("---> Result : " + result);
System.out.println("------->to int : " + (int)result );
}
}
}
output >
Today's Start Date String : 2016-09-20 00:00:00
Today's Start Date Long: 1474297200000
Yesterday's Start Date String : 2016-09-19 23:30:00
Yesterday Start Date Long : 1474295400000
Today's End Date String : 2016-09-20 21:30:00
Today's End Date Long : 1474374600000
c: 500
Yesterday's long value : 1474295400000
Today's long value : 1474374600000
---> Sum : 2948670000000
---> Result : 250
------->to int : 250
I changed the 'todaySeatedEndDateStr' variable's HH:mm:ss,
but always get the 250.
How can I fix this problem?
plz help me..
a and b are both measured in milliseconds since January 1970, so they are roughly the same even though a is yesterday and b is today. So b / (a + b) is very close to a half, and half of 500 is 250.
If I interpret your graph correctly, you want to do this instead:
long midnight = todayStartDate.getTime();
long result = (long) ((float) (b - midnight) / (float) (b - a) * c);
Now I am taking the time since midnight in proportion to the time since a yesterday. Please try and see if it works for you.
Midnight of earlier period’s start to end of later period?
Looks like you have over-complicated the original problem. Seems your problem picture wants elapsed time from midnight of the date of the earlier period to a later moment. If not so, please edit your Question to state in plain conversational English what is the problem statement. And why do you use words "yesterday" and "today" if the date-time values are hard-coded?
java.time
You are using troublesome old legacy date-time classes now supplanted by the java.time classes.
We parse as LocalDateTime objects because your inputs lack info about offset-from-UTC or time zone. If you want to account for issues such as Daylight Saving Time (DST), use ZonedDateTime instead.
To parse, we replace the SPACE in the middle with a T to comply with ISO 8601 standard.
LocalDateTime earlierStart = LocalDate.parse( "2016-09-19 23:30:00".replace( " " , "T" ) );
LocalDateTime laterStop = LocalDate.parse( "2016-09-20 21:30:00".replace( " " , "T" ) );
To get the midnight ending of the starting point, we need to go through the LocalDate. We move to the start of the next day because getting the last moment of the day is problematic with an endlessly divisible fractional second.
LocalDate localDateOfStartNextDay = earlierStart.toLocalDate().plusDays( 1 );
LocalDateTime newDayAfterStart = localDateOfStartNextDay.atStartOfDay();
Now capture the elapsed time as a Duration with a resolution of nanoseconds.
Duration duration = Duration.between( newDayAfterStart , laterStop );
This code may not be exactly your solution, given that your Question is confusing. But I think you can see that working with the java.time classes will be less convoluted that trying to do math on count-from-epoch numbers.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The question is to get day numbers of February of any year. My code is like this:
public static void main(String[] args) {
System.out.println("2014-02 has " + getDaysOfFeb(2014) + "days");
System.out.println("2016-02 has " + getDaysOfFeb(2016) + "days");
}
public static int getDaysOfFeb(int year) {
Calendar c = Calendar.getInstance();
// set year-01-31
c.set(year, 0, 31);
long lastDayofJan = c.getTimeInMillis();
// set year-03-01
c.set(year, 2, 1);
long firstDayOfMar = c.getTimeInMillis();
int date = (int) ((firstDayOfMar - lastDayofJan) / 1000 / 60 / 60 / 24);
}
I got Jan 31st and Mar 1st, I use the difference of time to calculate the day numbers. But the result is:
2014-02 has 29days
2016-02 has 30days
I don't understand why.
When I do like this:
public static int getDaysOfFeb(int year) {
Calendar c = Calendar.getInstance();
// set year-01-31
c.set(year, 2, 1);
c.add(Calendar.DATE, -1); // last day of Feb
int date = c.get(Calendar.DATE);
return date;
}
The result is right, as follow:
2014-02 has 28days
2016-02 has 29days
Does anyone know what the difference is here?
It is exactly how it should be. The difference between March, 1 and January, 31 is one day more than the number of days in February. In general, the difference between the same days in two consecutive months is the number of days in the earliest of these two months. So, the difference between March, 1 and February, 1 is the number of days in February, as well as the difference between March, 10 and February, 10 (and any other day). The difference between April, 1 and March, 1 is always 31 (the number of days in March) and so on.
Not that this is an exact answer. But I wrote a quick Java program a while ago that will generate a calendar for pretty much whatever month/year you want. The example falls directly in line with what you're trying to do.
Here is the code running on TutorialsPoint:
Calendar in Java
Code:
import java.util.Calendar;
public class calDays {
/**
* #param args
*/
static Calendar today = Calendar.getInstance();
static int curDay = today.get(Calendar.DAY_OF_MONTH);
static int curMonth = today.get(Calendar.MONTH);
static int curYear = today.get(Calendar.YEAR);
public static void main(String[] args) {
drawCal(curMonth,curYear);
drawCal(5,1969);
drawCal(4,2001);
}
public static void drawCal(Integer monthIs, Integer yearIs){
System.out.println(""+getMonth(monthIs)+" "+yearIs);
System.out.println("S M T W T F S ");
int calDayBox =0;
Calendar monthtd = Calendar.getInstance();
monthtd.set(Calendar.DAY_OF_MONTH,1);
monthtd.set(Calendar.MONTH, monthIs);
monthtd.set(Calendar.YEAR, yearIs);
int daysInMonth = monthtd.getActualMaximum(Calendar.DAY_OF_MONTH);
int allboxes=0;
//Draw leading days
int CalDaxBoxVal=1;
for (int xx=0;xx<monthtd.get(Calendar.DAY_OF_WEEK)-1;xx++){
System.out.print("_ ");
calDayBox++;
allboxes++;
}
for (int xx=calDayBox;xx<daysInMonth+calDayBox;xx++){
System.out.print(""+CalDaxBoxVal+ " ");
if (CalDaxBoxVal<10) System.out.print(" ");
CalDaxBoxVal++;
allboxes++;
if (allboxes%7==0) System.out.println();
}
System.out.println();
System.out.println();
}
public static String getMonth(Integer whichMonth){
String monthsAre[] = new String[12];
monthsAre[0]="January";
monthsAre[1]="February";
monthsAre[2]="March";
monthsAre[3]="April";
monthsAre[4]="May";
monthsAre[5]="June";
monthsAre[6]="July";
monthsAre[7]="August";
monthsAre[8]="September";
monthsAre[9]="October";
monthsAre[10]="November";
monthsAre[11]="December";
return monthsAre[whichMonth];
}
}
Change your first method to something like this.
Calendar c = Calendar.getInstance();
c.set(year, 1, 1);
long firstDayOfFeb= c.getTimeInMillis();
c.set(year, 2, 1);
long firstDayOfMar = c.getTimeInMillis();
int date = (int) ((firstDayOfMar - firstDayOfFeb) / 1000 / 60 / 60 / 24);
return date;
In your calculation you are actually calculating from last day of january to 1 st dat of March, where as you should start from 1 st day of Feb to 1st day of march for correct answer. The problem is with calculation.
This can be easily answered with simple mathematics.
If you are subtracting 0 from 30, (30 - 0 = ?) you get 30.
If you are subtracting 1 from 30, (30 - 1 = ?) you get 29.
Pretend 0 is February 0th (which is equivalent to January 31st)
Pretend 30 is February 30th (which is equivalent to March 1st on a leap year)
So therefore, March 1st - January 31st must be 30 days.
In order to get the desired number of days, you must subtract 1 from 30, and not 0 from 30.
Pretend 1 is February 1st
Pretend 30 is February 30th (which is equivalent to March 1st on a leap year)
Therefore, you would need to subtract March 1st from February 1st in order to get the correct number of days in February.
tl;dr
YearMonth.parse( "2014-02" ).lengthOfMonth()
Avoid old date-time classes
The Question and other Answers use troublesome old legacy date-time classes bundled with the earliest versions of Java. Now supplanted by the java.time classes.
YearMonth
Among the java.time classes is YearMonth to represent, well, a year and month.
Note that in java.time the months have sane numbering, 1-12 for January-December (unlike the crazy 0-11 in old date-time classes).
YearMonth ym = YearMonth.parse( "2014-02" );
Or you can make use of the handy Month enum.
YearMonth ym = YearMonth.of( 2014 , Month.FEBRUARY );
Interrogate for the number of days in that month by calling lengthOfMonth.
int lengthOfMonth = ym.lengthOfMonth() ;
You can ask if the year of that year-month is a Leap Year by calling isLeapYear.
boolean isLeapYear = ym.isLeapYear();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Been wrestling with this problem for a while, would love some input.
The problem I want to solve collects all of the dates in one specific year which fall on a particular day of the week, for example, every Tuesday in 2014. The dates are stored in an ArrayList<Date>. This list is then returned.
Also have to validate to make sure the year is not 0 and the day of the week submitted must be a number between 1-7.
If there are any issues, I would love to know what I have screwed up.
public List<Date> getDatesforDayOfWeek(int year, int dayOfWeek) throws InvalidDateException, ParseException {
List<Date> dateList = new ArrayList<>();
if (year <= 0 || (1 > dayOfWeek && dayOfWeek > 7)) {
throw new InvalidDateException("Year or day of week is invalid.");
} else {
Calendar newCal = Calendar.getInstance();
newCal.set(YEAR, year);
newCal.set(DAY_OF_YEAR, 1);
while (newCal.get(YEAR) < year + 1) {
int currentDayOfWeek = newCal.get(DAY_OF_WEEK);
Date newDate = null;
if (currentDayOfWeek >= dayOfWeek) {
int dayOfMonth = newCal.get(DAY_OF_MONTH);
String strDayOfMonth = String.valueOf(dayOfMonth);
String strYear = String.valueOf(year);
DateUtility d1 = new DateUtility();
Date passDate = newCal.getTime();
String weekDay = d1.getWeekDayNameAbbreviation(passDate);
String monthAbbreviation = d1.getMonthAbbreviation(passDate);
String finalString = new String();
finalString.concat(weekDay).concat(" ").
concat(monthAbbreviation).concat(" ").
concat(strDayOfMonth).concat(" ").
concat(strYear);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd YYYY");
Date theDate = format.parse(finalString);
dateList.add(theDate);
}
newCal.add(Calendar.DATE, 1);
}
}
return (dateList);
}
Your question fails to specify which is first day of the week, but things are further complicated by your method for testing the current day of the week. Let's start with validating days of the week by using the Calendar standard,
private static boolean isValidDayOfWeek(int dayOfWeek) {
switch (dayOfWeek) {
// Seven days of the week.
case Calendar.SUNDAY: case Calendar.MONDAY: case Calendar.TUESDAY:
case Calendar.WEDNESDAY: case Calendar.THURSDAY: case Calendar.FRIDAY:
case Calendar.SATURDAY:
return true;
}
return false;
}
It then follows that we can do something like,
public static List<Date> getDatesforDayOfWeek(int year, int dayOfWeek) {
List<Date> dateList = new ArrayList<>();
if (year <= 0 || !isValidDayOfWeek(dayOfWeek)) {
return null;
} else {
Calendar newCal = Calendar.getInstance();
newCal.set(Calendar.YEAR, year);
newCal.set(Calendar.DAY_OF_YEAR, 1);
// First, let's loop until we're at the correct day of the week.
while (newCal.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
newCal.add(Calendar.DAY_OF_MONTH, 1);
}
// Now, add the Date to the List. Then add a week and loop (stop
// when the year changes).
do {
dateList.add(newCal.getTime());
newCal.add(Calendar.DAY_OF_MONTH, 7);
} while (newCal.get(Calendar.YEAR) == year);
}
return dateList;
}
Leaving us with main(). So, to get every Tuesday in 2014 you could then use -
public static void main(String[] args) {
List<Date> tuesdays = getDatesforDayOfWeek(2014, Calendar.TUESDAY);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (Date d : tuesdays) {
System.out.println(df.format(d));
}
}
tl;dr
startOfYear // `Year.of( 2019 ).atDay( 1 )` gets the first day of the year.
.datesUntil( startOfYear.plusYears( 1 ) ) // Generate a stream of incrementing `LocalDate` objects.
.filter( // Pull out the dates that are a Tuesday.
t -> t.getDayOfWeek().equals( DayOfWeek.TUESDAY )
)
.collect( Collectors.toList() ) // Return results in a `List` of `LocalDate` objects.
ISO 8601
The ISO 8601 standard for date-time work defines Monday as the first day of week, identified by number 1. Sunday is 7.
Avoid j.u.Date & .Calendar
The java.util.Date and .Calendar classes bundled with java are notoriously troublesome. Avoid them. They have been supplanted in Java 8 by the new java.time package. That package was inspired by Joda-Time, an alternative that remains an active viable project with some advantages.
Both Joda-Time and java.time use ISO 8601 by default.
Date-Only
For this Question, we need only dates, not time-of-day or time zones. Both Joda-Time and java.time offer a LocalDate class for this purpose.
java.time
Use Year.of and LocalDate::plusYears to determine the bounds of a year, yielding a pair of LocalDate objects for each first-day-of-year.
LocalDate startOfYear = Year.of( 2019 ).atDay( 1 ); // Determine first day of the year.
LocalDate startOfFollowingYear = startOfYear.plusYears( 1 );
Loop, incrementing the date one day at a time. If that date happens to be a Tuesday, add it to our collection.
LocalDate localDate = startOfYear;
List < LocalDate > tuesdays = new ArrayList <>( 55 ); // Set initialCapacity to maximum number of tuesdays in a year. Probably 53, but I'll go with 55 for good measure.
while ( localDate.isBefore( startOfFollowingYear ) )
{
if ( localDate.getDayOfWeek().equals( DayOfWeek.TUESDAY ) )
{
tuesdays.add( localDate );
}
// Set up the next loop.
localDate = localDate.plusDays( 1 );
}
System.out.println( tuesdays );
See this code run live at IdeOne.com.
[2019-01-01, 2019-01-08, 2019-01-15, 2019-01-22, 2019-01-29, 2019-02-05, 2019-02-12, 2019-02-19, 2019-02-26, 2019-03-05, 2019-03-12, 2019-03-19, 2019-03-26, 2019-04-02, 2019-04-09, 2019-04-16, 2019-04-23, 2019-04-30, 2019-05-07, 2019-05-14, 2019-05-21, 2019-05-28, 2019-06-04, 2019-06-11, 2019-06-18, 2019-06-25, 2019-07-02, 2019-07-09, 2019-07-16, 2019-07-23, 2019-07-30, 2019-08-06, 2019-08-13, 2019-08-20, 2019-08-27, 2019-09-03, 2019-09-10, 2019-09-17, 2019-09-24, 2019-10-01, 2019-10-08, 2019-10-15, 2019-10-22, 2019-10-29, 2019-11-05, 2019-11-12, 2019-11-19, 2019-11-26, 2019-12-03, 2019-12-10, 2019-12-17, 2019-12-24, 2019-12-31]
Or get fancy with functional lambda syntax. The LocalDate::datesUntil method generates a stream, in Java 9 and later. Then filter the stream by a match on DayOfWeek.TUESDAY.
LocalDate startOfYear = Year.of( 2019 ).atDay( 1 );
Stream < LocalDate > stream = startOfYear.datesUntil( startOfYear.plusYears( 1 ) );
List < LocalDate > tuesdays = stream.filter( t -> t.getDayOfWeek().equals( DayOfWeek.TUESDAY ) ).collect( Collectors.toList() );
Joda-Time
Here is some example code in Joda-Time 2.4 for collecting all the Tuesdays in a year.
int year = 2014;
String input = year + "-01-01";
LocalDate localDateInput = LocalDate.parse( input );
LocalDate firstTuesday = localDateInput.withDayOfWeek ( DateTimeConstants.TUESDAY );
LocalDate tuesday = firstTuesday; // for incrementing by week.
List<LocalDate> list = new ArrayList<>();
while ( tuesday.getYear() == year ) {
list.add( tuesday );
tuesday.plusWeeks( 1 );
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I think your main problem lies in this condition
if (currentDayOfWeek >= dayOfWeek) {
since that will count any day that is "higher" than the day you want. If you pass 3, it will also count any day that is higher than 3, which isn't what you want.
the condition should be
if (currentDayOfWeek == dayOfWeek) {
I also recommend you use Calendar getTime method instead of parsing a String to get your Date.
I would to get the number of the half month od the year starting from a date.
For example, I have 13-Mar-2012, and I have 6 as result.
I've tried with Calendar class, but doesn't work properly:
Calendar cal = (GregorianCalendar) Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH,13);
cal.set(Calendar.MONTH, 2);
cal.set(Calendar.YEAR, 2012);
int weekNum = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println("Weeknum:" + ((weekNum/2)));
Can anyone help me?
Assuming Half month as defined here: http://en.wikipedia.org/wiki/Half-month
Calendar cal = (GregorianCalendar) Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 13);
cal.set(Calendar.MONTH, 2);
cal.set(Calendar.YEAR, 2012);
// remember, we have a zero based month
int halfMonth = cal.get( Calendar.MONTH ) * 2 + 1;
// 1-15 is first half-month 16-end of month is second
int remainder = cal.get( Calendar.DAY_OF_MONTH ) / 16;
halfMonth += remainder;
System.out.println( halfMonth );
Calendar cal = (GregorianCalendar) Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH,13);
cal.set(Calendar.MONTH, 2);
cal.set(Calendar.YEAR, 2012);
int hafMonthCount = cal.get(Calendar.DAY_OF_YEAR) / 14 ;
//here you must multiply by 2 :)
System.out.println("HalfMonthCount:" + hafMonthCount );
---updated
As the concept you use is not implemented in Java (in french we have this concept of quizaine for 14 days but in english I can't say), you must compute it by yourself.
Details to show by example what happens with your code. Assume we have the following four different values of WEEK_OF_YEAR:
WEEK_OF_YEAR: 1
WEEK_OF_YEAR: 2
WEEK_OF_YEAR: 3
WEEK_OF_YEAR: 4
What will happen if we divide these values by 2?
WEEK_OF_YEAR: 1 (weekNum/2) = 1/2 = 0
WEEK_OF_YEAR: 2 (weekNum/2) = 2/2 = 1
WEEK_OF_YEAR: 3 (weekNum/2) = 3/2 = 1
WEEK_OF_YEAR: 4 (weekNum/2) = 4/2 = 2
So the issue with your code is that it will result in the first week of the year resulting in a value 0. So what you'd want to be doing in your code is to replace the (weekNum/2) with ((weekNum + 1)/2).
If the astronomy Half-Month is intended (not to be confused with an astronomy fortnight), then the Answer by jarrad is correct. But we have more modern classes at our disposal now, the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z );
Get the month number, 1-12 for January-December.
int monthNumber = ld.getMonthValue(); // 1-12.
Multiply that month number by two, as there are two month-halves in every month. If early in the month, subtract one (so 6 becomes 5, for example).
int adjustment = ( ld.getDayOfMonth() < 16 ) ? 1 : 0 ; // If first half of month, back off the half-month-number by 1.
int halfMonthNumber = ( ( monthNumber * 2 ) - adjustment ); // 1-24.
The astronomy Half-Month labels each with a English letter, A-Y while omitting I. So we extract a letter from this subset alphabet of 24 letters by the half-month-number.
int index = ( halfMonthNumber - 1 ); // Subtract one for zero-based counting.
String alphaCode = "ABCDEFGHJKLMNOPQRSTUVWXY".substring( index , index + 1 );
I have not run that code, just typed off the top of my head. Use at your own risk, and please fix if needed.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
How do I find the difference in Days between two Joda-Time DateTime instances?
With ‘difference in days’ I mean if start is on Monday and end is on Tuesday I expect a return value of 1 regardless of the hour/minute/seconds of the start and end dates.
Days.daysBetween(start, end).getDays() gives me 0 if start is in the evening and end in the morning.
I'm also having the same issue with other date fields so I was hoping there would be a generic way to 'ignore' the fields of lesser significance.
In other words, the months between Feb and 4 March would also be 1, as would the hours between 14:45 and 15:12 be. However the hour difference between 14:01 and 14:55 would be 0.
Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.
// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate()).getDays());
// prints 1
Going via a LocalDate sidesteps the whole issue.
Days Class
Using the Days class with the withTimeAtStartOfDay method should work:
Days.daysBetween(start.withTimeAtStartOfDay() , end.withTimeAtStartOfDay() ).getDays()
you can use LocalDate:
Days.daysBetween(new LocalDate(start), new LocalDate(end)).getDays()
tl;dr
java.time.temporal.ChronoUnit.DAYS.between(
earlier.toLocalDate(),
later.toLocalDate()
)
…or…
java.time.temporal.ChronoUnit.HOURS.between(
earlier.truncatedTo( ChronoUnit.HOURS ) ,
later.truncatedTo( ChronoUnit.HOURS )
)
java.time
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
The equivalent of Joda-Time DateTime is ZonedDateTime.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
Apparently you want to count the days by dates, meaning you want to ignore the time of day. For example, starting a minute before midnight and ending a minute after midnight should result in a single day. For this behavior, extract a LocalDate from your ZonedDateTime. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate localDateStart = zdtStart.toLocalDate() ;
LocalDate localDateStop = zdtStop.toLocalDate() ;
Use the ChronoUnit enum to calculate elapsed days or other units.
long days = ChronoUnit.DAYS.between( localDateStart , localDateStop ) ;
Truncate
As for you asking about a more general way to do this counting where you are interested the delta of hours as hour-of-the-clock rather than complete hours as spans-of-time of sixty minutes, use the truncatedTo method.
Here is your example of 14:45 to 15:12 on same day.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime start = ZonedDateTime.of( 2017 , 1 , 17 , 14 , 45 , 0 , 0 , z );
ZonedDateTime stop = ZonedDateTime.of( 2017 , 1 , 17 , 15 , 12 , 0 , 0 , z );
long hours = ChronoUnit.HOURS.between( start.truncatedTo( ChronoUnit.HOURS ) , stop.truncatedTo( ChronoUnit.HOURS ) );
1
This does not work for days. Use toLocalDate() in this case.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data.
I use this:
public static int getDaysBetween(DateTime earlier, DateTime later)
{
return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
}
By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.
java.time.Period
Use the java.time.Period class to count days.
Since Java 8 calculating the difference is more intuitive using LocalDate, LocalDateTime to represent the two dates
LocalDate now = LocalDate.now();
LocalDate inputDate = LocalDate.of(2018, 11, 28);
Period period = Period.between( inputDate, now);
int diff = period.getDays();
System.out.println("diff = " + diff);
(KOTLIN) For Difference between a constant date and current date (Joda)
You can use Days.daysBetween(jodaDate1,jodaDate2)
Here is an example:
val dateTime: DateTime = DateTime.parse("14/09/2020",
DateTimeFormat.forPattern("dd/MM/yyyy"))
val currentDate = DateTime.now()
//To calculate the days in between
val dayCount = Days.daysBetween(dateTime,currentDate).days
//Set Value to TextView
binding.daysCount.text = dayCount.toString()
DateTime dt = new DateTime(laterDate);
DateTime newDate = dt.minus( new DateTime ( previousDate ).getMillis());
System.out.println("No of days : " + newDate.getDayOfYear() - 1 );
public static int getDifferenceIndays(long timestamp1, long timestamp2) {
final int SECONDS = 60;
final int MINUTES = 60;
final int HOURS = 24;
final int MILLIES = 1000;
long temp;
if (timestamp1 < timestamp2) {
temp = timestamp1;
timestamp1 = timestamp2;
timestamp2 = temp;
}
Calendar startDate = Calendar.getInstance(TimeZone.getDefault());
Calendar endDate = Calendar.getInstance(TimeZone.getDefault());
endDate.setTimeInMillis(timestamp1);
startDate.setTimeInMillis(timestamp2);
if ((timestamp1 - timestamp2) < 1 * HOURS * MINUTES * SECONDS * MILLIES) {
int day1 = endDate.get(Calendar.DAY_OF_MONTH);
int day2 = startDate.get(Calendar.DAY_OF_MONTH);
if (day1 == day2) {
return 0;
} else {
return 1;
}
}
int diffDays = 0;
startDate.add(Calendar.DAY_OF_MONTH, diffDays);
while (startDate.before(endDate)) {
startDate.add(Calendar.DAY_OF_MONTH, 1);
diffDays++;
}
return diffDays;
}