This question already has answers here:
How to get the first day of the current week and month?
(15 answers)
Closed 6 years ago.
I would like to fetch the first date of a week.
My input is going to be a String type like 07/26/2014".
I need to get the first date of week in which the above date(07/26/2014) falls.
I need output date in MM/dd/YYYY format .
basically I need output as 07/21/2014.
Please give me the java program. I have done upto this
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yy");
String date ="07/26/2014";
Date Currentdate = formatter1.parse(date);
int currentday=Currentdate.getDay();
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
int startDay=currentday-calendar.getFirstDayOfWeek();
Currentdate.setDate(contacteddate.getDate()-startDay);
System.out.println(contacteddate.getDate());
}
The above code only gives me the date.. I need date along with month and year in "MM/dd/YYYY"
Please help
I would do it this way
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
After setting time to Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
use
calendar.set(Calendar.DAY_OF_WEEK, 1)
and then
simpleFormat.format(calendar.getTime());
This will help you.
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 1; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
The problem with all presented solutions so far is not to specify what exactly the week definition is. Week definitions are either technically specified like in ISO-8601-standard (Monday as first day of week and first calendar week of year containing at least four days), or they use localized rules (for example in US a week begins by Sunday!).
Due to the requirement that the OP wants "07/21/2014" as first day of week around "07/26/2014" it seems that ISO-8601 is what the OP really wants. But code like
Calendar calendar = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
...
will not work in a country like US or an application server located in US. Counter example:
// simulating a US-located application server where this code is running
GregorianCalendar calendar = new GregorianCalendar(Locale.US);
calendar.set(2014, Calendar.JULY, 26);
calendar.getTime(); // avoid ugly side effects in calendar date handling
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(calendar.getTime())); // output: 2014-07-20
If the OP changes the choosen locale to let's say Locale.FRANCE (applying ISO-rules) then the OP can achieve his goal using the traditional Java-date-and-time-library.
It should be noted however that week handling using the java.util.Calendar-stuff is often confusing and hard. For example: Without the strange getter-call (calendar.getTime()) which enforces update of internal calculation the result would be: 2014-07-06 (surely not what OP wants).
Therefore I recommend following other libraries to choose a generic approach compatible with different week definitions:
a) Java-8 (built-in library JSR-310 aka java.time):
LocalDate date = LocalDate.of(2014, 7, 26);
TemporalField dowField = WeekFields.ISO.dayOfWeek();
date = date.with(dowField, dowField.range().getMinimum());
System.out.println(date); // output: 2014-07-21
Note: Avoid code like date.with(DayOfWeek.MONDAY) because in that case the java.time-library cannot evaluate the underlying week rules which possibly deviate from ISO-8601 (here choosen: WeekFields.ISO, but it might also be WeekFields.SUNDAY_START).
b) my own library Time4J:
PlainDate date = PlainDate.of(2014, 7, 26);
date = date.with(Weekmodel.ISO.localDayOfWeek().minimized());
System.out.println(date); // output: 2014-07-21
c) If you know in advance that you only want ISO-8601-week-rules then you might also consider a simpler approach in Java-8 or instead its predecessor JodaTime:
// Java-8 applying ISO-8601-rules
LocalDate date = LocalDate.of(2014, 7, 26);
date = date.with(DayOfWeek.MONDAY);
// Joda-Time
LocalDate date = new LocalDate(2014, 7, 26);
date = date.dayOfWeek().withMinimumValue();
Related
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DATE));
int months = 1;
calender.add(Calendar.MONTH, months );
String time = sdf .format(calender .getTime());
System.out.println(time);
Since current month is April and last date is 2020-04-30
Next month last date I should get 2020-05-31
but I am getting last date as 2020-05-30
Any thing am i doing wrong ?
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work. It’s much nicer to work with than the old classes Calendar and SimpleDateFormat.
LocalDate endOfNextMonth =
YearMonth // Represent an entire month in a particular year.
.now(ZoneId.of("Europe/Volgograd")) // Capture the current year-month as seen in a particular time zone. Returns a `YearMonth` object.
.plusMonths(1) // Move to the next month. Returns another `YearMonth` object.
.atEndOfMonth(); // Determine the last day of that year-month. Returns a `LocalDate` object.
String time = endOfNextMonth.toString(); // Represent the content of the `LocalDate` object by generating text in standard ISO 8601 format.
System.out.println("Last day of next month: " + time);
Output when running today:
Last day of next month: 2020-05-31
A YearMonth, as the name maybe says, is a year and month without day of month. It has an atEndOfMonth method that conveniently gives us the last day of the month as a LocalDate. A LocalDate is a date without time of day, so what we need here. And its toString method conveniently gives the format that you wanted (it’s ISO 8601).
Depending on the reason why you want the last day of another month there are a couple of other approaches you may consider. If you need to handle date ranges that always start and end on month boundaries, you may either:
Represent your range as a range of YearMonth objects. Would this free you from knowing the last day of the month altogether?
Represent the end of your range as the first of the following month exclusive. Doing math on the 1st of each month is simpler since it is always day 1 regardless of the length of the month.
What went wrong in your code?
No matter if using Calendar, LocalDate or some other class you need to do things in the opposite order: first add one month, then find the end of the month. As you know, months have different lengths, so the important part is getting the end of that month where you want to get the last day. Putting it the other way: setting either a LocalDate or a Calendar to the last day of the month correctly sets it to the last day of the month in qustion but does not instruct it to stay at the last day of the month after subsequent changes to its value, such as adding a month. If you add a month to April 29, you get May 29. If you add a month to April 30, you get May 30. Here it doesn’t matter that 30 is the last day of April while 30 is not the last day of May.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
You'd better use LocalDate like this:
LocalDate now = LocalDate.now();
LocalDate lastDay = now.withDayOfMonth(now.lengthOfMonth());
LocalDate nextMonth = lastDay.plusMonths(1);
Don't use deprecated classes from java.util.*.
Use classes from java.time.*.
Example with LocalDate :
public class Testing {
public static void main(String args[]) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
int months = 1;
date = date.plusMonths(months);
date = date.withDayOfMonth(date.lengthOfMonth());
System.out.println(date.format(dateTimeFormatter));
}
}
Output :
2020-05-31
Example with Calendar :
public class Testing {
public static void main(String args[]) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
int months = 1;
calender.add(Calendar.MONTH, months);
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DAY_OF_MONTH));
String time = sdf.format(calender.getTime());
System.out.println(time);
}
}
Output :
2020-05-31
Hello guys i have a tricky question for you that i really cant find a solution out there.
What i want to do is to have 3 date/time inputs on simpledateformat
Date 1
Date 2
Date 3
and basicaly i want to get difference of months days hours and minutes from date 1 - date2 and result of those 2 dates to be added on the firth date
for example 11/3/2017 12:30 - 7/3/2017 = 4 days and ADD that to current date 13/3/2017 13:30 + 4 days and 1 hour = 17/3/2017 14:30
i know how to get the diference in days hours and minutes , i cant get the second part of adding the result to the current date
any ideas?
thank you in dvance
Use Calendar class to add days and hours
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
To decrement dates just add negative number, for example:
int yourDays = -daysVariable;
int yourHours = -hoursVariable; //
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //decrement days
cal.add(Calendar.HOUR_OF_DAY, yourHours); //decrement hours
cal.getTime(); //to get Date instance
Get a date object using the simpledate format
Because it is an object of the same type
Comparison is possible
I think you need to use getTime and add days throught miliseconds.
For example, if you can get the difference of days you should use something like this
date1.getTime() + 24*60*60*1000*4
(where 4 is the difference you want to add)
You can use Calendar too.
Thank you all for your ultra fast replies!
I solved it by using Mij Solution
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
To add days and
tis code to decrese days
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, -yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, -yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
and to control if date is bigget than my current date i used this condition
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
it returns -1 if the date is past from current
+1 if date is bigger that current or whatever
and 0 if dates are equal
again thank you!
I am trying to write code to find the Day difference between tow date but Calendar.getInstance() keep getting the date for previous month instead of current month
for example :Current 17/7/2014 it get 17/6/2014
my code :
TextView textview=(TextView) findViewById (R.id.textView1);
Calendar cal = Calendar.getInstance();
Calendar startDate=Calendar.getInstance();
startDate.set(Calendar.DAY_OF_MONTH, 1);
startDate.set(Calendar.MONTH,1);
startDate.set(Calendar.YEAR, 2013);
long diff=(((cal.getTimeInMillis()-startDate.getTimeInMillis())/(1000*60*60*24))+1);
String sdiff=String.valueOf(diff);
String stt=cal.get(Calendar.YEAR) +"_"+cal.get(Calendar.MONTH)+"_"+cal.get(Calendar.DAY_OF_MONTH);
textview.setText(stt);
Months start at 0, not at 1, but you really don't have to worry about this if you don't use magic numbers when getting or setting month but instead use the constants. So not this:
startDate.set(Calendar.MONTH,1); // this is February!
but rather
startDate.set(Calendar.MONTH, Calendar.JANUARY);
Months in Java's Calendar start with 0 for January, so July is 6, not 7.
Calendar.MONTH javadocs:
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0
Add 1 to the result of get.
(cal.get(Calendar.MONTH) + 1)
This also affects your set call. You can either subtract 1 when passing a month number going in, or you can use a Calendar constant, e.g. Calendar.JANUARY.
You can also use a SimpleDateFormat to convert it to your specific format, without having to worry about this quirk.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
String stt = sdf.format(cal.getTime());
I am working on a program that asks the user which day they would like to see a lunch menu for. They can enter any day by name (Monday, Tuesday, etc.). This works well, but I would also like them to be able to enter "Today" and then have the program get the current date and then check the menu for that value.
How would I do this?
You can use java.util.Calendar:
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
This is the exact answer of the question,
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
System.out.println(new SimpleDateFormat("EE", Locale.ENGLISH).format(date.getTime()));
System.out.println(new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date.getTime()));
Result (for today):
Sat
Saturday
As of Java 8 and its new java.time package:
DayOfWeek dayOfWeek = DayOfWeek.from(LocalDate.now());
or
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
Java 8 :
LocalDate.now().getDayOfWeek().name()
The date is selected by the user using a drop down for year, month and day. I have to compare the user entered date with today's date. Basically see if they are the same date. For example
the user entered 02/16/2012. And if today is 02/16/2012 then I have to display a message. How do I do it?
I tried using milliseconds but that gives out wrong results.
And what kind of object are you getting back? String, Calendar, Date? You can get that string and compare it, at least that you think you'll have problems with order YYYY MM DD /// DD MM YYY in that case I suggest to create a custom string based on your spec YYYYMMDD and then compare them.
Date d1 = new Date();
Date d2 = new Date();
String day1 = d1.getYear()+"/"+d1.getMonth()+"/"+d1.getDate();
String day2 = d2.getYear()+"/"+d2.getMonth()+"/"+d2.getDate();
if(day1.equals(day2)){
System.out.println("Same day");
}
Dates in java are moments in time, with a resolution of "to the millisecond". To compare two dates effectively, you need to first set both dates to the "same time" in hours, minutes, seconds, and milliseconds. All of the "setTime" methods in a java.util.Date are depricated, because they don't function correctly for the internationalization and localization concerns.
To "fix" this, a new class was introduced GregorianCalendar
GregorianCalendar cal1 = new GregorianCalendar(2012, 11, 17);
GregorianCalendar cal2 = new GregorianCalendar(2012, 11, 17);
return cal1.equals(cal2); // will return true
The reason that GregorianCalendar works is related to the hours, minutes, seconds, and milliseconds being initialized to zero in the year, month, day constructor. You can attempt to approximate such with java.util.Date by using deprecated methods like setHours(0); however, eventually this will fail due to a lack of setMillis(0). This means that to use the Date format, you need to grab the milliseconds and perform some integer math to set the milliseconds to zero.
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date1.setTime((date1.getTime() / 1000L) * 1000L);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
date2.setTime((date2.getTime() / 1000L) * 1000L);
return date1.equals(date2); // now should do a calendar date only match
Trust me, just use the Calendar / GregorianCalendar class, it's the way forward (until Java adopts something more sophisticated, like joda time.
There is two way you can do it. first one is format both the date in same date format or handle date in string format.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date1 = sdf.format(selectedDate);
String date2 = sdf.format(compareDate);
if(date1.equals(date2)){
}else{
}
Or
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-date->);
if(!toDate.before(nowDate))
//display your report
else
// don't display the report
Above answers are correct but consider using JodaTime - its much simpler and intuitive API.
You could set DateTime using with* methods and compare them.
Look at this answer