Java year display coming out in 3 digits - java

I'm trying to do a simple console display in Eclipse and my time and date are coming directly from the computer. For some reason, the year display is only coming out in 3 characters instead of 4, and I have no idea why. Any help would be amazing. Here's the code:
public class InClass3 implements ActionListener
{
static int month, day, year, hour, minute;
public static void Display()
{
int i;
String []Date = new String[3];
String []Hello = new String[3];
String []Time = new String[3];
Date();
Time();
for (i = 0; i < 3; i ++)
{
switch (i)
{
case 0:
Hello[0] = "HELLO WORLD";
Date[0] = month + "/" + day + "/" + year;
Time[0] = hour + ":" + minute;
break;
case 1:
Hello[1] = "hello world";
Date[1] = year + "." + month + "." + day;
if (hour > 12)
{
hour = hour - 12;
Time[1] = hour + ":" + minute + "pm";
}
else
{
Time[1] = hour + ":" + minute + "am";
}
break;
case 2:
Hello[2] = "Hello World";
Date[2] = day + " " + month + " " + year;
Time[2] = hour + ":" + minute;
break;
default: System.out.println("Fatal error occured. Please relaunch this application.");
}
System.out.println(Hello[i] + "\n" + Date[i] + "\n" + Time[i]);
}
}
#SuppressWarnings("deprecation")
public static void Time()
{
Date t = new Date();
hour = t.getHours();
minute = t.getMinutes();
}
#SuppressWarnings("deprecation")
public static void Date()
{
Date d = new Date();
year = d.getYear();
month = d.getMonth();
day = d.getDay();
}
public static void main(String[] args)
{
Display();
}
#Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
}
}
And this is what it's outputting:
HELLO WORLD
3/5/115
14:47
hello world
115.3.5
2:47pm
Hello World
5 3 115
2:47
I would obviously like it to display the 2015 - not the 115. Thanks for any insight.

year = d.getYear() + 1900;
That's because the year is stored as the number of years since 1900.
However, there are some good reasons why Date is deprecated. You should use Calendar instead.

Do not rely on Date's get-like methods. They are deprecated.
The getYear() method returns the date "minus 1900", so that 1999 is 99, 2000 is 100, etc. You have a Y2K bug!
Returns:
the year represented by this date, minus 1900.
Instead, use a SimpleDateFormat object to control your formatting.
SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy");
System.out.println(sdf.format(new Date()));

https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#getYear--
getYear
#Deprecated !!!
public int getYear()
Deprecated. As of JDK version 1.1,
replaced by Calendar.get(Calendar.YEAR) - 1900.
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Returns:
the year represented by this date, minus 1900.
You could consider newer options from Java 8
https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#now--

tl;dr
Year.now( ZoneID.of( "America/Montreal" ) )
.getValue()
Details
You are using troublesome old date-time classes now supplanted by 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 today = LocalDate.now( z );
Interrogate the LocalDate for its year number.
int year = today.getYear() ;
Alternatively, use Year class.
int yearNumber = Year.now( ZoneId.of( "Pacific/Auckland" ) ).getValue() ;
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.

Related

How to obtain elapsed years from string

I have the string date "3.9.1991". And I want to obtain how many years have passed since the date. For example 23. How can I achieve it using Calendar or Date?
EDIT:
I have been trying this:
private String parseVkBirthday(String birthdayString) {
// 3.9.1991
SimpleDateFormat formatter = new SimpleDateFormat("d.M.yyyy");
String formattedDate = null;
Calendar date = Calendar.getInstance();
int year = 0;
try {
Date currentDate = new Date();
Date birthdayDate = formatter.parse(birthdayString);
Log.d(LOG_TAG, "year1 = " + currentDate.getTime() + " year2 = " + birthdayDate.getTime());
long diff = currentDate.getTime() - birthdayDate.getTime();
birthdayDate.setTime(diff);
date.setTime(birthdayDate);
year = date.get(Calendar.YEAR);
} catch (ParseException e) {
e.printStackTrace();
}
return "" + year;
}
But it returns me 1993.
Answer:
There are while 3 ways for solving this problem:
1) As codeaholicguy answered, we can use Joda-Time library(what I prefer for Android).
2) As Basil Bourque answered, we can use ThreeTen-Backport library for using java.time classes from java 8.
3) And we can use java 8 and classes from java.time.
Thanks to everyone.
Use SimpleDateFormat and Period of Joda-Time library, example below:
String pattern = "dd.MM.yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date date = format.parse("3.9.1991");
System.out.println(date);
Period period = new Period(date.getTime(), (new Date()).getTime());
System.out.println(period.getYears());
String fullDate="3.9.1991";
String[] splitDate=fullDate.split(".");
int year=Integer.parseInt(splitDate[2]);
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int passedYears=currentYear-year;
Calendar.YEAR can be used to add or subtract year from current date in the same fashion we added days and month into date.
http://javarevisited.blogspot.in/2012/12/how-to-add-subtract-days-months-years-to-date-time-java.html
sample program:
import java.util.Calendar;
public class Years {
public static void main(String[] args) {
//create Calendar instance
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//add year to current date using Calendar.add method
now.add(Calendar.YEAR,1);
System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//substract year from current date
now =Calendar.getInstance();
now.add(Calendar.YEAR,-100);
System.out.println("date before 100 years : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
}
}
http://forgetcode.com/Java/1568-Adding-or-Subtracting-Years-to-Current-Date#
Based on example code by xrcwrn with the Joda-Time 2.8 library:
// get the current year with #xrcwm's code
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
DateTime myDateTime = new DateTime(thedate.getTime()); // joda DateTime object
// get he current date
DateTime currentDateTime = new DateTime();
// get the years value
long years = Years.between(currentDateTime, myDateTime).getYears()
The code above should give you the correct value. Mind you, this code may have some syntax errors.
As a side note, Java 8 has a time package which seems to provide more of the same functionality.
java.time
The new java.time package in Java 8 and later supplants the old java.util.Date/.Calendar & SimpleTextFormat classes.
First parse the string using new DateTimeFormatter class. Do not use SimpleTextFormat. And read the doc as there may be subtle differences in the symbol codes between the old and new classes.
Get today's date, to calculate elapsed years. Note that we need a time zone. Time zone is crucial in determining a date. A new day dawns earlier in Paris, for example, than it does in Montréal.
The Period class considers a span of time as a number of years, months and days not tied to any points on the timeline.
The between method uses the "Half-Open" approach common to date-time handling. The beginning is inclusive while the ending is exclusive.
The default formatting of java.time follows the ISO 8601 standard. Apply formatter if you wish a different string representation of your date-time values.
String input = "3.9.1991" ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d.M.yyyy") ;
LocalDate then = LocalDate.parse( input, formatter ) ;
ZoneId zone = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( zone ) ; // Specify time zone to get your locality’s current date.
Period period = Period.between( then , today ) ;
int years = period.getYears() ;
System.out.println( "Between " + then + " and " + today + " is " + years + " years.");
Between 1991-09-03 and 2015-07-09 is 23 years.
Joda-Time
Android currently lacks Java 8 features. So you cannot use java.time. Unless perhaps the ThreeTen-Backport project (a) supports the classes used in the above example and (b) works on Android (I do not know about either).
Alternatively, you can use Joda-Time, the third-party library that inspired java.time. The Joda-Time code version of the above code example would be very similar. In this case, java.time and Joda-Time parallel one another with similar classes.
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
mydate.setTime(thedate);
//breakdown
System.out.println("year -> "+mydate.get(Calendar.YEAR));
Reference

Android get week day names between two dates

I want to get day names between two dates with simple Java, without using any third party library.
I want to get names like Saturday, Sunday, Monday between two days inclusive both.
/**
*
* #param startDate
* #param endDate
* #return Start Date and End Date are <b>Inclusive</b>, days returned between these two dates
*/
protected List<String> getWeekDayNames(Date startDate, Date endDate) {
List<String> days = new ArrayList<String>();
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
days.add(this.formatDayOfWeek(startCal.getTime()));
return Collections.unmodifiableList(days);
}
// swap values
if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do {
days.add(this.formatDayOfWeek(startCal.getTime()));
startCal.add(Calendar.DAY_OF_MONTH, 1);
} while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
return Collections.unmodifiableList(days);
}
Usage:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 15);
List<String> list = new Test().getWeekDayNames(new Date(), cal.getTime());
System.out.println(list);
Output:
[SATURDAY, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Joda-Time
Usually I would suggest the Joda-Time library, a popular replacement for the notoriously troublesome java.util.Date & java.util.Calendar classes bundled with Java. But the Question requires no third-party libraries.
java.time.*
So, instead of Joda-Time, my code example below uses the new java.time.* package bundled with Java 8. These classes are inspired by Joda-Time, but are entirely re-architected. They are defined by JSR 310. For more information, see the new Tutorial from Oracle.
The solution is quite simple. Boils down to this one-line fragment…
DayOfWeek.from( zonedDateTime ).getDisplayName( TextStyle.FULL, Locale.US );
For fun, I tossed in an extra line to show how easy it is to localize. In this case I show the French as well as US English word for day-of-week.
Here is the entire snippet, ready to run if you import java.time.* and java.time.format.*.
ZoneId timeZone = ZoneId.of( "America/New_York" );
ZonedDateTime start = ZonedDateTime.now( timeZone );
ZonedDateTime stop = start.plusDays( 2 );
// Usually spans of time are handled in a "half-open" manner, meaning start is inclusive and stop is exclusive.
// But the Question required both start and stop to be inclusive. So add "1".
long days = java.time.temporal.ChronoUnit.DAYS.between( start, stop ) + 1L;
System.out.println( days + " days from " + start + " to " + stop + " inclusive…");
for ( int i = 0; i < days; i++ ) {
ZonedDateTime zonedDateTime = start.plusDays( i );
String dayOfWeek = DayOfWeek.from( zonedDateTime ).getDisplayName( TextStyle.FULL, java.util.Locale.US );
String dayOfWeek_Français = DayOfWeek.from( zonedDateTime ).getDisplayName( TextStyle.FULL, java.util.Locale.FRENCH );
System.out.println( "zonedDateTime: " + zonedDateTime + " dayOfWeek: " + dayOfWeek + " dayOfWeek_Français: " + dayOfWeek_Français );
}
When run…
3 days from 2014-02-08T06:06:33.335-05:00[America/New_York] to 2014-02-10T06:06:33.335-05:00[America/New_York] inclusive…
zonedDateTime: 2014-02-08T06:06:33.335-05:00[America/New_York] dayOfWeek: Saturday dayOfWeek_Français: samedi
zonedDateTime: 2014-02-09T06:06:33.335-05:00[America/New_York] dayOfWeek: Sunday dayOfWeek_Français: dimanche
zonedDateTime: 2014-02-10T06:06:33.335-05:00[America/New_York] dayOfWeek: Monday dayOfWeek_Français: lundi

java.util.Date and getYear()

I am having the following problem in Java (I see some people are having
a similar problem in JavaScript but I'm using Java)
System.out.println(new Date().getYear());
System.out.println(new GregorianCalendar().getTime().getYear());
System.out.println(this.sale.getSaleDate().getYear());
System.out.println(this.sale.getSaleDate().getMonth());
System.out.println(this.sale.getSaleDate().getDate());
returns
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 1
I/System.out( 4274): 11
I don't understand the 112 bit which I thought would have been 2012.
What's going on? Is the
java.util.Date class unusable? I am storing this as a field in several
of my classes to store a date and time. What should I do?
In addition to all the comments, I thought I might add some code on how to use java.util.Date, java.util.Calendar and java.util.GregorianCalendar according to the javadoc.
//Initialize your Date however you like it.
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
//Add one to month {0 - 11}
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
According to javadocs:
#Deprecated
public int getYear()
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Returns:
the year represented by this date, minus 1900.
See Also:
Calendar
So 112 is the correct output. I would follow the advice in the Javadoc or use JodaTime instead.
Use date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);
Don't use Date, use Calendar:
// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR); // 2012
int month = date.get(Calendar.MONTH); // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH); // 5
It supports time as well:
Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY); // 15
int minute = dateTime.get(Calendar.MINUTE); // 16
int second = dateTime.get(Calendar.SECOND); // 17
The java documentation suggests to make use of Calendar class instead of this deprecated way
Here is the sample code to set up the calendar object
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Here is the sample code to get the year, month, etc.
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));
Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them
Please note that the month are 0 based. January is 0th month.
tl;dr
LocalDate.now() // Capture the date-only value current in the JVM’s current default time zone.
.getYear() // Extract the year number from that date.
2018
java.time
Both the java.util.Date and java.util.Calendar classes are legacy, now supplanted by the java.time framework built into Java 8 and later.
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.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
If you want only the date without time-of-day, use LocalDate. This class lacks time zone info but you can specify a time zone to determine the current date.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( zoneId );
You can get the various pieces of information with getYear, getMonth, and getDayOfMonth. You will actually get the year number with java.time!
int year = localDate.getYear();
2016
If you want a date-time instead of just a date, use ZonedDateTime class.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
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 the java.time classes.
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 & Java 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.
Yup, this is in fact what's happening. See also the Javadoc:
Returns:
the year represented by this date, minus 1900.
The getYear method is deprecated for this reason. So, don't use it.
Note also that getMonth returns a number between 0 and 11. Therefore, this.sale.getSaleDate().getMonth() returns 1 for February, instead of 2. While java.util.Calendar doesn't add 1900 to all years, it does suffer from the off-by-one-month problem.
You're much better off using JodaTime.
Java 8 LocalDate class is another option to get the year from a java.util.Date,
int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear();
Another option is,
int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
There are may ways of getting day, month and year in java.
You may use any-
Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);
Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1 = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);
LocalDateTime ldt1 = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy3 = ldt1.format(format1);
System.out.println("Formatted Date 3: " + mmddyyyy3);
LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);
LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy5 = ldt3.format(format2);
System.out.println("Formatted Date 5: " + mmddyyyy5);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3 = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);
Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4 = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);
Date date4 = new Date();
int day5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);
Date date5 = new Date();
int day6 = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6 = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);
System.out.println("Formatted Date 9: " + mmddyyyy9);
Year.now()
There's an easier way to use the java.time library in Java 8+. The expression:
java.time.Year.now().getValue()
returns the current year as a four-digit int, using your default time zone. There are lots of options for different time ZoneIds, Calendars and Clocks, but I think this is what you will want most of the time. If you want the code to look cleaner (and don't need any other java.time.*.now() functions), put:
import static java.time.Year.now;
at the top of your file, and call:
now().getValue()
as needed.
This behavior is documented in the java.util.Date -class documentation:
Returns a value that is the result of subtracting 1900 from the year
that contains or begins with the instant in time represented by this
Date object, as interpreted in the local time zone.
It is also marked as deprecated. Use java.util.Calendar instead.
try{
int year = Integer.parseInt(new Date().toString().split("-")[0]);
}
catch(NumberFormatException e){
}
Much of Date is deprecated.

How can I find the number of years between two dates?

I am trying to determine an age in years from a certain date. Does anyone know a clean way to do this in Android? I have the Java api available obviously, but the straight-up java api is pretty weak, and I was hoping that Android has something to help me out.
EDIT: The multiple recommendations to use Joda time in Android worries me a bit due to Android Java - Joda Date is slow and related concerns. Also, pulling in a library not shipped with the platform for something this size is probably overkill.
import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;
public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(YEAR) - a.get(YEAR);
if (a.get(MONTH) > b.get(MONTH) ||
(a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
diff--;
}
return diff;
}
public static Calendar getCalendar(Date date) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
return cal;
}
Note: as Ole V.V. noticed, this won't work with dates before Christ due how Calendar works.
tl;dr
ChronoUnit.YEARS.between(
LocalDate.of( 2010 , 1 , 1 ) ,
LocalDate.now( ZoneId.of( "America/Montreal" ) )
)
Test for zero years elapsed, and one year elapsed.
ChronoUnit.YEARS.between(
LocalDate.of( 2010 , 1 , 1 ) ,
LocalDate.of( 2010 , 6 , 1 )
)
0
ChronoUnit.YEARS.between(
LocalDate.of( 2010 , 1 , 1 ) ,
LocalDate.of( 2011 , 1 , 1 )
)
1
See this code run at Ideone.com.
java.time
The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.
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…).
LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;
LocalDate stop = LocalDate.now( ZoneId.of( "America/Montreal" ) );
long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );
Dump to console.
System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;
start: 2010-01-01 | stop: 2016-09-06 | years: 6
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, 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….
I would recommend using the great Joda-Time library for everything date related in Java.
For your needs you can use the Years.yearsBetween() method.
I apparently can't comment yet, but I think you can just use the DAY_OF_YEAR to workout if you should adjust the years down one (copied and modified from current best answer)
public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
if (a.get(Calendar.DAY_OF_YEAR) > b.get(Calendar.DAY_OF_YEAR)) {
diff--;
}
return diff;
}
public static Calendar getCalendar(Date date) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
return cal;
}
Similarly you could probably just diff the ms representations of the time and divide by the number of ms in a year. Just keep everything in longs and that should be good enough most of the time (leap years, ouch) but it depends on your application for the number of years and how performant that function has to be weather it would be worth that kind of hack.
I know you have asked for a clean solution, but here are two dirty once:
static void diffYears1()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar1 = Calendar.getInstance(); // now
String toDate = dateFormat.format(calendar1.getTime());
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
String fromDate = dateFormat.format(calendar2.getTime());
// just simply add one year at a time to the earlier date until it becomes later then the other one
int years = 0;
while(true)
{
calendar2.add(Calendar.YEAR, 1);
if(calendar2.getTimeInMillis() < calendar1.getTimeInMillis())
years++;
else
break;
}
System.out.println(years + " years between " + fromDate + " and " + toDate);
}
static void diffYears2()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar1 = Calendar.getInstance(); // now
String toDate = dateFormat.format(calendar1.getTime());
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
String fromDate = dateFormat.format(calendar2.getTime());
// first get the years difference from the dates themselves
int years = calendar1.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR);
// now make the earlier date the same year as the later
calendar2.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
// and see if new date become later, if so then one year was not whole, so subtract 1
if(calendar2.getTimeInMillis() > calendar1.getTimeInMillis())
years--;
System.out.println(years + " years between " + fromDate + " and " + toDate);
}
Here's what I think is a better method:
public int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
EDIT
Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
class YearsBetweenDates {
public static int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
private static class TestCase {
public Calendar date1;
public Calendar date2;
public int expectedYearDiff;
public String comment;
public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
this.date1 = date1;
this.date2 = date2;
this.expectedYearDiff = expectedYearDiff;
this.comment = comment;
}
}
private static TestCase[] tests = {
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2015, Calendar.JULY, 15),
1,
"exactly one year"),
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 14),
2,
"one day less than 3 years"),
new TestCase(
new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
new GregorianCalendar(2017, Calendar.MAY, 3),
1,
"a year and a half"),
new TestCase(
new GregorianCalendar(2016, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 15),
1,
"leap years do not compare correctly"),
};
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (TestCase t : tests) {
int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
System.out.println(t.comment + ": " +
df.format(t.date1.getTime()) + " -> " +
df.format(t.date2.getTime()) + " = " +
diff + ": " + result);
}
}
}
a handy one if you don't want to border Calendar, Locale, or external library:
private static SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
public static Integer toDate8d(Date date) {
String s;
synchronized (YYYYMMDD) { s = YYYYMMDD.format(date); } // SimpleDateFormat thread safety
return Integer.valueOf(s);
}
public static Integer yearDiff(Date pEarlier, Date pLater) {
return (toDate8d(pLater) - toDate8d(pEarlier)) / 10000;
}
If you don't want to calculate it using java's Calendar you can use Androids Time class It is supposed to be faster but I didn't notice much difference when i switched.
I could not find any pre-defined functions to determine time between 2 dates for an age in Android. There are some nice helper functions to get formatted time between dates in the DateUtils but that's probably not what you want.
// int year =2000; int month =9 ; int day=30;
public int getAge (int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);//current day
cal.set(year, month, day);// here ur date
noofyears = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--noofyears;
}
if(noofyears < 0)
throw new IllegalArgumentException("age < 0");
System.out.println(noofyears);
return noofyears;
This will work and if you want the number of years replace 12 to 1
String date1 = "07-01-2015";
String date2 = "07-11-2015";
int i = Integer.parseInt(date1.substring(6));
int j = Integer.parseInt(date2.substring(6));
int p = Integer.parseInt(date1.substring(3,5));
int q = Integer.parseInt(date2.substring(3,5));
int z;
if(q>=p){
z=q-p + (j-i)*12;
}else{
z=p-q + (j-i)*12;
}
System.out.println("The Total Months difference between two dates is --> "+z+" Months");
Thanks #Ole V.v for reviewing it: i have found some inbuilt library classes which does the same
int noOfMonths = 0;
org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat
.forPattern("yyyy-MM-dd");
DateTime dt = formatter.parseDateTime(startDate);
DateTime endDate11 = new DateTime();
Months m = Months.monthsBetween(dt, endDate11);
noOfMonths = m.getMonths();
System.out.println(noOfMonths);
Try this:
int getYear(Date date1,Date date2){
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
Integer.parseInt(simpleDateformat.format(date1));
return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));
}

How to get the first day of the current week and month?

I have the date of several events expressed in milliseconds[1], and I want to know which events are inside the current week and the current month, but I can't figure out how to obtain the first day (day/month/year) of the running week and convert it to milliseconds, the same for the first day of the month.
[1]Since January 1, 1970, 00:00:00 GMT
This week in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
This month in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of the month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Start of the month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// get start of the next month
cal.add(Calendar.MONTH, 1);
System.out.println("Start of the next month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
The first day of week can be determined with help of java.util.Calendar as follows:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
long firstDayOfWeekTimestamp = calendar.getTimeInMillis();
The first day of month can be determined as follows:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DATE) > 1) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of month.
}
long firstDayOfMonthTimestamp = calendar.getTimeInMillis();
Pretty verbose, yes.
Java 7 will come with a much improved Date and Time API (JSR-310). If you can't switch yet, then you can as far use JodaTime which makes it all less complicated:
DateTime dateTime = new DateTime(timestamp);
long firstDayOfWeekTimestamp = dateTime.withDayOfWeek(1).getMillis();
and
DateTime dateTime = new DateTime(timestamp);
long firstDayOfMonthTimestamp = dateTime.withDayOfMonth(1).getMillis();
java.time
The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.
The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.
Instant
The Instant class represents a moment on the timeline in UTC.
The java.time framework has a resolution of nanoseconds, or 9 digits of a fractional second. Milliseconds is only 3 digits of a fractional second. Because millisecond resolution is common, java.time includes a handy factory method.
long millisecondsSinceEpoch = 1446959825213L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
millisecondsSinceEpoch: 1446959825213 is instant: 2015-11-08T05:17:05.213Z
ZonedDateTime
To consider current week and current month, we need to apply a particular time zone.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
In zoneId: America/Montreal that is: 2015-11-08T00:17:05.213-05:00[America/Montreal]
Half-Open
In date-time work, we commonly use the Half-Open approach to defining a span of time. The beginning is inclusive while the ending in exclusive. Rather than try to determine the last split-second of the end of the week (or month), we get the first moment of the following week (or month). So a week runs from the first moment of Monday and goes up to but not including the first moment of the following Monday.
Let's the first day of the week, and last. The java.time framework includes a tool for that, the with method and the ChronoField enum.
By default, java.time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).
ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );
That week runs from: 2015-11-02T00:17:05.213-05:00[America/Montreal] to 2015-11-09T00:17:05.213-05:00[America/Montreal]
Oops! Look at the time-of-day on those values. We want the first moment of the day. The first moment of the day is not always 00:00:00.000 because of Daylight Saving Time (DST) or other anomalies. So we should let java.time make the adjustment on our behalf. To do that, we must go through the LocalDate class.
ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
firstOfWeek = firstOfWeek.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );
That week runs from: 2015-11-02T00:00-05:00[America/Montreal] to 2015-11-09T00:00-05:00[America/Montreal]
And same for the month.
ZonedDateTime firstOfMonth = zdt.with ( ChronoField.DAY_OF_MONTH , 1 );
firstOfMonth = firstOfMonth.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextMonth = firstOfMonth.plusMonths ( 1 );
That month runs from: 2015-11-01T00:00-04:00[America/Montreal] to 2015-12-01T00:00-05:00[America/Montreal]
YearMonth
Another way to see if a pair of moments are in the same month is to check for the same YearMonth value.
For example, assuming thisZdt and thatZdt are both ZonedDateTime objects:
boolean inSameMonth = YearMonth.from( thisZdt ).equals( YearMonth.from( thatZdt ) ) ;
Milliseconds
I strongly recommend against doing your date-time work in milliseconds-from-epoch. That is indeed the way date-time classes tend to work internally, but we have the classes for a reason. Handling a count-from-epoch is clumsy as the values are not intelligible by humans so debugging and logging is difficult and error-prone. And, as we've already seen, different resolutions may be in play; old Java classes and Joda-Time library use milliseconds, while databases like Postgres use microseconds, and now java.time uses nanoseconds.
Would you handle text as bits, or do you let classes such as String, StringBuffer, and StringBuilder handle such details?
But if you insist, from a ZonedDateTime get an Instant, and from that get a milliseconds-count-from-epoch. But keep in mind this call can mean loss of data. Any microseconds or nanoseconds that you might have in your ZonedDateTime/Instant will be truncated (lost).
long millis = firstOfWeek.toInstant().toEpochMilli(); // Possible data loss.
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….
Attention!
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
is good idea, but there is some issue:
For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday).
And today is 1 (Sunday). In this case calendar.add not called.
So, correct way is change ">" to "!=":
while (calendar.get(Calendar.DAY_OF_WEEK) != calendar.getFirstDayOfWeek()) {...
You can use the java.time package (since Java8 and late) to get start/end of day/week/month.
The util class example below:
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class DateUtil {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public static LocalDateTime startOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
}
public static LocalDateTime endOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
}
public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
}
//note that week starts with Monday
public static LocalDateTime startOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
//note that week ends with Sunday
public static LocalDateTime endOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
}
public static LocalDateTime startOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime endOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
}
public static long toMills(final LocalDateTime localDateTime) {
return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
}
public static Date toDate(final LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
}
public static String toString(final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
}
#Test
public void test() {
//day
final LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
System.out.println("Start of day: " + toString(startOfDay()));
System.out.println("End of day: " + toString(endOfDay()));
System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
final LocalDateTime yesterday = now.minusDays(1);
System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
final LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
//week
System.out.println("Start of week: " + toString(startOfWeek()));
System.out.println("End of week: " + toString(endOfWeek()));
System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
final LocalDateTime previousWeek = now.minusWeeks(1);
System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
final LocalDateTime nextWeek = now.plusWeeks(1);
System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
//month
System.out.println("Start of month: " + toString(startOfMonth()));
System.out.println("End of month: " + toString(endOfMonth()));
System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
final LocalDateTime previousMonth = now.minusMonths(1);
System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
final LocalDateTime nextMonth = now.plusMonths(1);
System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
}
}
Test output:
Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false
I have created some methods for this:
public static String catchLastDayOfCurrentWeek(String pattern) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
return calendarToString(cal, pattern);
}
public static String catchLastDayOfCurrentWeek(String pattern) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.add(Calendar.MILLISECOND, -1);
return calendarToString(cal, pattern);
}
public static String catchTheFirstDayOfThemonth(Integer month, pattern padrao) {
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
return calendarToString(cal, pattern);
}
public static String catchTheLastDayOfThemonth(Integer month, String pattern) {
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.set(cal.get(Calendar.YEAR), month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendarToString(cal, pattern);
}
public static String calendarToString(Calendar calendar, String pattern) {
if (calendar == null) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
return format.format(calendar.getTime());
}
You can see more here.
To get the first day of the month, simply get a Date and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.
private static Date firstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
return calendar.getTime();
}
First day of the week is the same thing, but using Calendar.DAY_OF_WEEK instead
private static Date firstDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);
return calendar.getTime();
}
In this case:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY); <---- is the current hour not 0 hour
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
So the Calendar.HOUR_OF_DAY returns 8, 9, 12, 15, 18 as the current running hour.
I think will be better change such line by:
c.set(Calendar.HOUR_OF_DAY,0);
this way the day always begin at 0 hour
Get First date of next month:-
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
String selectedDate="MM-dd-yyyy like 07-02-2018";
Date dt = df.parse(selectedDate);`enter code here`
calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1);
String firstDate = df.format(calendar.getTime());
System.out.println("firstDateof next month ==>" + firstDate);
A one-line solution using Java 8 features
In Java
LocalDateTime firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay(); // 2020-06-08 00:00 MONDAY
LocalDateTime firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay(); // 2020-06-01 00:00
// Convert to milliseconds:
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
In Kotlin
val firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay() // 2020-06-08 00:00 MONDAY
val firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay() // 2020-06-01 00:00
// Convert to milliseconds:
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
You should be able to convert your number to a Java Calendar, e.g.:
Calendar.getInstance().setTimeInMillis(myDate);
From there, the comparison shouldn't be too hard.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
/**
This Program will display day for, 1st and last days in a given month and year
#author Manoj Kumar Dunna
Mail Id : manojdunna#gmail.com
*/
public class DayOfWeek {
public static void main(String[] args) {
String strDate = null;
int year = 0, month = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter YYYY/MM: ");
strDate = sc.next();
Calendar cal = new GregorianCalendar();
String [] date = strDate.split("/");
year = Integer.parseInt(date[0]);
month = Integer.parseInt(date[1]);
cal.set(year, month-1, 1);
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_YEAR, -1);
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
}
}
Simple Solution:
package com.util.calendarutil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class CalUtil {
public static void main(String args[]){
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date dt = null;
try {
dt = df.parse("23/01/2016");
} catch (ParseException e) {
System.out.println("Error");
}
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
Date startDate = cal.getTime();
cal.add(Calendar.DATE, 6);
Date endDate = cal.getTime();
System.out.println("Start Date:"+startDate+"End Date:"+endDate);
}
}
i use this trick to get the first day of the current month
note the order is
1 for Sunday
2 for Monday
3 for Tuesday
.... and so on
Calendar cal = new GregorianCalendar();
int startDay = cal.get(Calendar.DAY_OF_YEAR) % 7 + 1;
System.out.println(startDay);
public static void main(String[] args) {
System.out.println(getMonthlyEpochList(1498867199L,12,"Monthly"));
}
public static Map<String,String> getMonthlyEpochList(Long currentEpoch, int noOfTerms, String timeMode) {
Map<String,String> map = new LinkedHashMap<String,String>();
int month = 0;
while(noOfTerms != 0) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, month);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date monthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date monthLastDay = calendar.getTime();
map.put(getMMYY(monthFirstDay.getTime()), monthFirstDay + ":" +monthLastDay);
month--;
noOfTerms--;
}
return map;
}

Categories

Resources