how to get minimum and maximum date from given month in java - java

how to get minimum and maximum date from given month in java using java.util.Calendar.

The minimum is always the 1st of this month. The maximum can be determined by adding 1 to month and subtracting 1 from the Calendar day field.

This could be done this way:
c = ... // get calendar for month you're interested in
int numberOfDays = c.getActualMaximum(Calendar.DAY_OF_MONTH)
You could find minimum and maximum value the same way for any of components of the date.

Have you tried the following?
After setting your calendar object to your desired month,
calendar.getActualMaximum(Calendar.DATE);
For the minimum, I suppose it's always the first.
Hope that helps.

Minimum date is always 1
and Maximum date can be calculate as
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
int year = 2010;
int month = Calendar.FEBRUARY;
int date = 1;
int maxDay =0;
calendar.set(year, month, date);
System.out.println("First Day: " + formatter.format(calendar.getTime()));
//Getting Maximum day for Given Month
maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(year, month, maxDay);
System.out.println("Last Day: " + formatter.format(calendar.getTime()));
Hopefully this will helps

I got solution as below,
public void ddl_month_valueChange(ValueChangeEvent event) {
int v_month = Integer.parseInt(event.getNewValue().toString()) - 1;
java.util.Calendar c1 = java.util.Calendar.getInstance();
c1.set(2011, v_month, 1);
Date d_set_att_from = c1.getTime();
cal_att_from_date.setValue(d_set_att_from);
c1.add(java.util.Calendar.MONTH, 1);
c1.add(java.util.Calendar.DATE, -1);
Date d_set_att_to = c1.getTime();
cal_att_to_date.setValue(d_set_att_to); }

Related

How do find day number(integer) of last day in the current month

I have specific date and i want to find last day number(integer) of month. I am using following code but always return current of date.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) sdf.parse(year+"-"+(month<10?("0"+month):month)+"-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date dt = (Date) calendar.getTime(); -> dt is return current date always
example: my date = 2018/04/30 and i want to find 30.
I couldnt find answer at site.
Thnx
If using Java 8 (or higher), don't use Calendar. If using Java 6 or 7, you might want to consider using the ThreeTen Backport. In either case, use the Java Time API.
Using Java Time
Since input is int year and int month, use YearMonth.
To find last day number of month, call lengthOfMonth().
To get the date at the end of month, call atEndOfMonth().
Demo
int year = 2020;
int month = 2;
int lastDay = YearMonth.of(year, month).lengthOfMonth();
System.out.println(lastDay);
LocalDate date = YearMonth.of(year, month).atEndOfMonth();
System.out.println(date);
Output
29
2020-02-29
Using Joda-Time
If you don't have Java 8, and already use Joda-Time, do it this way:
Demo
int year = 2020;
int month = 2;
int lastDay = new LocalDate(year, month, 1).dayOfMonth().getMaximumValue();
System.out.println(lastDay);
LocalDate date = new LocalDate(year, month, 1).dayOfMonth().withMaximumValue();
System.out.println(date);
Output
29
2020-02-29
Using Calendar
If you insist on using Calendar, call getActualMaximum(Calendar.DAY_OF_MONTH) as also mentioned in other answers.
Since input is int year and int month, don't build and parse a string, just set Calendar fields directly. Note that "month" in Calendar is zero-based.
Demo
int year = 2020;
int month = 2;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(year, month - 1, 1);
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
Date date = calendar.getTime();
System.out.println(lastDay);
System.out.printf("%tF%n", date);
Output
29
2020-02-29
have specific date and i want to find last day number(integer) of month
getActualMaximum() is what you are looking for here.
Calendar cal = Calendar.getInstance();
cal.setTime(parsedDate);
cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Calendar calendar =Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
calendar.roll(Calendar.DATE, -1);
int lastDate=calendar.get(Calendar.DATE);
You can use calendar for that, like this:
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Or, if you have joda, which is usually better:
DateTime d = new DateTame(dt);
d.dayOfMonth().getMaximumValue();
First, how are you getting the year to be used?
it should be simple by using Java Time LocalDate:
import java.time.*;
import static java.time.Month.*;
import static java.time.temporal.TemporalAdjusters.*;
import static java.time.temporal.ChronoField.*;
int lastDay = LocalDate.now() // or whatever date you want
.with(Month.of(yourMonth))
.with(lastDayOfMonth())
.get(DAY_OF_MONTH);
// or, if you have year and month, and want to find the corresponding last day
int lastDay = LocalDate.of(yourYear, yourMonth, 1)
.with(lastDayOfMonth())
.get(DAY_OF_MONTH);

Java getter and setter for a date field

I am beginning Java and I have been ask to write a class myDate. Such a class has fields for year, month and day.
I should use the following syntax to set the date:
setDate(long timeElapsed)
I know that I can do the following:
Date tempDate = new Date();
long lngDate = tempDate.getTime();
System.out.println("lngDate: " + lngDate);
How do I calculate the "long timeElapsed" parameter from a given year, month and day?
Now, I should use GregorianCalendar to display the date, for which I have done the following:
GregorianCalendar cal = new GregorianCalendar(year, month, day);
System.out.println("Year: " + cal.YEAR);
System.out.println("Month: " + cal.MONTH);
System.out.println("Day: " + cal.DAY_OF_MONTH);
But the results I get are as follow:
Year: 1
Month: 2
Day: 5
How can I use GregorianCalendar to display a date in myDate class? I have been working on this issue for a while without success.
I will very much appreciate your feedback.
Respectfully,
Jorge Maldonado
Calendar.YEAR as well as MONTH and DAY_OF_THE_MONTH are constants to use in get() method. so
System.out.println("Year: " + cal.get(Calendar.YEAR));
System.out.println("Month: " + cal.get(Calendar.MONTH));
System.out.println("Day: " + cal.get(Calendar.DAY_OF_MONTH));
does what you need.
BTW on top you do not need to create new Date to get time value:
long lngDate = System.currentTimeMillis();
System.out.println("lngDate: " + lngDate);
value is the same. When new Date created it uses System.currentTimeMillis()
PS. Just keep in mind cal.get(Calendar.MONTH) returns month number -1. Jan is month 0, Feb is month 1 and so on.
Just call the following method to get the date as a long from a calendar:
cal.getTimeInMillis()
Here is the corresponding class:
public class MyDate {
public void setDate(long timeElapsed) {
final GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date(timeElapsed));
this.year = cal.get(Calendar.YEAR);
this.month = cal.get(Calendar.MONTH);
this.day = cal.get(Calendar.DAY_OF_MONTH);
}
public long getLong() {
final GregorianCalendar cal = new GregorianCalendar(this.year, this.month, this.day);
return cal.getTimeInMillis();
}
private int year, month, day;
}

Take away a single day using Calendar in Java?

I have an application that plugs into the Google Fit Api and returns the steps for the last 7 days, the method is below. As the screen shot shows though I wish to add the day to the step count.
I have tried many options to take away one day at a time for the 7 loop but had no luck, it just says the same day. Any help would be great thank you.
private void dumpDataSet(DataSet dataSet) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = DateFormat.getTimeInstance();
int i = 0;
for (DataPoint dp : dataSet.getDataPoints()) {
for(Field field : dp.getDataType().getFields()) { //loop 7 times
int test = dp.getValue(field).asInt();
String weekSteps= String.valueOf(test); //get weekday steps one at a time
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Calendar cal = Calendar.getInstance();
String weekday = sdf.format(cal.getTime());
String weekStepsFinal= weekSteps + " steps on " + weekday; //set Textfield to steps and the day
FeedItem item = new FeedItem();
item.setTitle(weekStepsFinal);
feedItemList.add(item);
}
}
}
There are 7 datasets btw.
If by "take away one day at a time" means that you want the days going backwards, then here's how:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
System.out.println("Last 7 days (starting today):");
Calendar cal = Calendar.getInstance(); // Initialized to today/now
for (int i = 0; i < 7; i++) {
System.out.println(" " + sdf.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, -1); // Update to previous day at same time-of-day
}
OUTPUT
Last 7 days (starting today):
Monday
Sunday
Saturday
Friday
Thursday
Wednesday
Tuesday
This will subtract 7 days from the calendar to get you the date 7 days ago:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -7).
To subtract one day use the following code :
int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Date currentDate = new Date();
long previousDay = currentDate.getTime()-DAY_IN_MILLIS;
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String day = sdf.format(previousDay);

Calendar - Get last day of previous month

I want to get the last day of the previous month.
But this doesnt seem to work:
Calendar cal = Calendar.getInstance();
Integer lastDay = cal.getInstance().getActualMaximum(cal.DAY_OF_MONTH);
cal.add(Calendar.MONTH, -1);
Integer prevMonth = cal.get(Calendar.MONTH);
Integer prevMonthYear = cal.get(Calendar.YEAR);
Integer lastDayPrevMonth = cal.getInstance().getActualMaximum(cal.DAY_OF_MONTH);
System.out.println("Previous month was: " + prevMonth + "-" + prevMonthYear);
System.out.println("Last day in previous month was: " + lastDayPrevMonth);
System.out.println("Last day in this month is: " + lastDay);
This outputs:
I/System.out﹕: Previous month was 10-2015
I/System.out﹕: Last day in previous month was 31
I/System.out﹕: Last day in this month is 31
So it's getting the previous month, that's november (10), giving that it is now december (11).
Last day in this month is also correct, but clearly, last day in previous month was not 31, but 30.
Why does the second getActualMaximum give the same "last-day-in-month" as the first, when I do the add -1 thing?
The problem in your current code is that you are calling multiple times the Calendar.getInstance() method, which returns the current date.
To obtain a Calendar which is the last day of the previous month, you can have the following:
public static void main(String... args) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
It subtracts one month from the current month and sets the day of month to its maximum value, obtained with getActualMaximum. Note that the month is 0-based in Calendar so January is actually 0.
You can use LocalDate as below:
LocalDate.now().withDayOfMonth(1).minusDays(1)
Try this, I think it will solve your problem:
/**
* Returns previous month date in string format
* #param date
* #return
*/
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
/**
* Returns previous to previous month date in string format
* #param date
* #return
*/
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}

Formatting java.sql.Date to yyyyMMdd

I am using the below code
#SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);
I am getting below output.
3914-02-09
39140209
Does any one know why there is 3914?
Thanks,
Mahesh
The javadoc for the constructor you're using java.sql.Date(int,int,int) reads (in part),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
so you should use (assuming you mean this year)
Date d = new Date (2015-1900,01,9);
From Java Docs,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Code
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
output
2014-01-09

Categories