How to set some days on Calendar.DAY_OF_WEEK - java

I need to set some days in method set. I try to use:
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
but with this way set only Wednesday.
Thank you and sorry for my english :)

The Calendar does not function as you expect it to. From the JavaDoc:
The Calendar class is an abstract class that provides methods for
converting between a specific instant in time and a set of calendar
fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for
manipulating the calendar fields, such as getting the date of the next
week. An instant in time can be represented by a millisecond value
that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT
(Gregorian).
Notice that the documentation states a specific instant in time. This implies the Calendar can only be based off of one point in time from epoch.
When you use the set method you are adjusting the specific instant in time through each call. So first it gets set to Monday then Wednesday.
You could use a List<Calendar> to store multiple Calendar instances set to your desired days.
public class CalendarTest {
public static void main(String[] args) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal2.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
List<Calendar> calendars = Arrays.asList(cal1, cal2);
}
}

public static String getDay(String day,String month,String year){
int mm = Integer.parseInt(month);
int dd = Integer.parseInt(day);
int yy = Integer.parseInt(year);
LocalDate dt = LocalDate.of(yy, mm, dd);
return dt.getDayOfWeek().toString().toUpperCase();
}

Related

getMonth getYear getDate giving errorneous result

I have a method to calculate the expiry date given manufacturing date of format("yyyy-MM-dd") and the months before the product could be used in int.First I tried with getYear getMonth getDate of Month class as follows I dint got errors results:
public void calculateExpiryDate(List<Item> items)
{
Iterator<Item> itr=items.iterator();
while(itr.hasNext())
{
Item i=itr.next();
Date md=i.getManufacturingDate();
int ubm=i.getUseBeforeMonths();
Calendar c=new GregorianCalendar(md.getYear(),md.getMonth(),md.getDate());
//System.out.println(c);
c.add(Calendar.MONTH, ubm);
Date exp=c.getTime();
i.setExpiryDate(exp);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy MM dd");
System.out.println(md+" "+ubm+" "+sdf.format(exp)+" "+" "+i.getId());
}
}
But when I Quit using it and used setTime instead it solved my problem.I want to know what mistake I was making before and why things don't work that day and if any mistake(cause I was not getting any compile time errors) what is it actually.Following is the version of same code giving proper results.
public void calculateExpiryDate(List<Item> items)
{
Iterator<Item> itr=items.iterator();
while(itr.hasNext())
{
Item i=itr.next();
Date md=i.getManufacturingDate();
int ubm=i.getUseBeforeMonths();
Calendar c=new GregorianCalendar();
c.setTime(md);
//System.out.println(c);
c.add(Calendar.MONTH, ubm);
Date exp=c.getTime();
i.setExpiryDate(exp);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy MM dd");
System.out.println(md+" "+ubm+" "+sdf.format(exp)+" "+" "+i.getId());
}
}
Your problem is that the constructor for GregorianCalendar expects the year as absolute value, but getYear() returns an offset to 1900.
A look into to the Java documentation reveals (beside that the used Date methods are all deprecated):
Date.getYear():
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.
GregorianCalendar:
year constructor parameter the value used to set the YEAR calendar field in the calendar
Whereas setTime(Date) used the value returned by md.getTime() which is number of milliseconds since January 1, 1970, 00:00:00 GMT.

Detect invalid date on Calendar.set()

I have this method that returns me a Date() changed by one of it's "fields" (DAY, MONTH, YEAR).
public static Date getDateChanged(Date date, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(field, value);
return cal.getTime();
}
However, cal.set() is unable to give an exception when the field we are trying to set is not compatible with the date in question. So, in this case:
Date date = new Date();
date = getDateChanged(date, Calendar.DAY_OF_MONTH, 29);
date = getDateChanged(date, Calendar.MONTH, 1); // feb
date is, in the end, 01/03/15, because Calendar.set() detects that February can't be set with day 29, so automatically set's date to the next possible day (I thinks this is how the routine works).
This is not so bad, however, in my case,
I want to detect that the date I'm trying to build is impossible and then start decrementing the day, so in this case what I'm trying to achieve is 28/02/15, how can I do this?
Example:
29/02/15 ===> 28/02/15
You can use cal.getActualMaximum(Calendar.DAY_OF_MONTH) to find the maximum days in the given month for your calendar instance.
This way, you can handle the case you mentioned above yourself.
Also see the answer here: Number of days in particular month of particular year?
You can use:
public void setLenient(boolean lenient)
Specifies whether or not date/time interpretation is to be lenient.
With lenient interpretation, a date such as "February 942, 1996" will
be treated as being equivalent to the 941st day after February 1,
1996. With strict (non-lenient) interpretation, such dates will cause an exception to be thrown. The default is lenient.
Parameters:
lenient - true if the lenient mode is to be turned on; false if it is to be turned off.
See Also:
isLenient(), DateFormat.setLenient(boolean)
This way you get exception when you pass something wrong :)
You can check the maximum value with getActualMaximum:
public static Date getDateChanged(Date date, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int maximum = calendar.getActualMaximum(field);
if (value > maximum) {
value = maximum;
}
cal.set(field, value);
return cal.getTime();
}
May be this solution will help you
public static Date getDateChanged(Date date, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(field, value);
if (field == Calendar.MONTH && cal.get(Calendar.MONTH) != value) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int month = (cal.get(Calendar.MONTH) - 1) < 0 ? 0 : (cal.get(Calendar.MONTH) - 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
return calendar.getTime();
}
return cal.getTime();
}

Android get difference in milliseconds between two dates

I have Integer fields:
currentYear,currentMonth,currentDay,currentHour,currentMinute and nextYear,nextMonth,nextDay,nextHour,nextMinute.
How I can get difference between those two spots in time in milliseconds.
I found a way using Date() object, but those functions seems to be depricated, so it's little risky.
Any other way?
Use GregorianCalendar to create the date, and take the diff as you otherwise would.
GregorianCalendar currentDay=new GregorianCalendar (currentYear,currentMonth,currentDay,currentHour,currentMinute,0);
GregorianCalendar nextDay=new GregorianCalendar (nextYear,nextMonth,nextDay,nextHour,nextMinute,0);
diff_in_ms=nextDay. getTimeInMillis()-currentDay. getTimeInMillis();
Create a Calendar object for currenDay and nextDay, turn them into longs, then subtract. For example:
Calendar currentDate = Calendar.getInstance();
Calendar.set(Calendar.MONTH, currentMonth - 1); // January is 0, Feb is 1, etc.
Calendar.set(Calendar.DATE, currentDay);
// set the year, hour, minute, second, and millisecond
long currentDateInMillis = currentDate.getTimeInMillis();
Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
long nextDateInMillis = nextDate.getTimeInMillis();
return nextDateInMillis - currentDateInMillis; // this is what you want
If you don't like the confusion around the Calendar class, you can check out the Joda time library.

Date picking and finding difference

I am a novice to Java programming using Netbeans. I have added jCalendar to my GUI to pick a date.
I have entered this line in Events -> "property change" code of jCalendar button,
Date date=jcalendar1.getDate();
So that I get the date immediately when it is changed. Am I right?
The purpose:
I want to find the difference in milliseconds from the afternoon (12:00 pm) of this date above to NOW (current date and time).
There are several programs showing the date difference but all have dates hardcoded and being a newbie i do not know how to replace it with the date that is picked. (also i am confused between the objects Date and Calendar, not able to understand the difference between them). For example, a piece from here:
http://www.java2s.com/Code/Java/Data-type/ReturnsaDatesetjusttoNoontotheclosestpossiblemillisecondoftheday.htm
if (day == null) day = new Date();
cal.setTime(day);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
return cal.getTime();
Here day is a Date object. How is cal (a calendar object) linked to it to enter the time. How should the cal object be defined first? How can I use this or anything else in your opinion for my program. A piece of code with detail comments will be more helpful
thanks!
Instead of using :
Date day = new Date();
Use:
Calendar cal = Calendar.getInstance();
cal.set (...);
Date date = new Date(cal.getTimeInMillis());
Worth abstracting this stuff out to a DateUtils class or similar, with something like the following:
public static Date create(int year, int month, int day, int hour, int minute, int second) {
return new Date(getTimeInMillis(year, month, day, hour, minute, second));
}
public static long getTimeInMillis(int year, int month, int day, int hour, int minute, int second, int milliseconds) {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, month, day, hour, minute, second);
cal.set(Calendar.MILLISECOND, milliseconds);
return cal.getTimeInMillis();
}

How can I set a Calendar with UTC time?

The posters here say that Date is always in UTC time. However, if I create a Date(), create a Calendar, and set the calendar time with the date, the time remains my local time (and I am not on UTC time.
I've tested this by printing out the calendar's date in a loop, subtracting an hour per loop. It's 11pm on the 19th of May here, and it takes 24 loops before the date changes to the 18th of May. It's currently 1pm UTC, so if the calendar were set properly it would only take 14 loops.
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
int index = 0;
for(; index > -30; index--)
{
System.out.println(index);
System.out.println(dateFormatter.format(calendar.getTime()));
System.out.println();
calendar.add(Calendar.HOUR, -1);
}
java.util.Calendar has a static factory method which takes a timezone.
Calendar.getInstance(java.util.TimeZone)
So you can say:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

Categories