I am doing an assignment and it involves using the GregorianCalendar. The specs say I need to use setLenient(false); how do I do this? I also need to set a constant date (1/1/2009) so that the first day of my program is always that.
It also says to access the day, month and year through this:
get(1) //returns the year
get(2) // returns the month
get(5) /// returns the day
To add n days to the date, call the add method with a field number of 5: add(5, n);
To subtract: add(5, -n);
Can someone please explain what that means and how to implement it?
Start by visiting the API docs here. These docs explain exactly what methods are available in a class in Java.
To get a Calendar for instance you can:
Calendar c = Calendar.getInstance();
You will see in the docs that there are actually a number of ways to get a Calendar and the default is a GregorianCalendar.
Once you have the Calendar object then you can call any method passing the necessary parameters. For example,
c.setLenient(true);
To use the get methods you have to specify the field that you wish to get.
int month = c.get(Calendar.MONTH);
and so on.
Create an instance of Calendar and call setLenient on it.
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
int month = cal.get(Calendar.MONTH);
UPDATE:
And since you only mentioned SimpleDateFormat in your comment, here's an example for it as well:
Date today = cal.getTime();
DateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd");
System.out.println(formatter.format(today));
Java Almanac is a good source for simple code snippet examples like these.
To create a GregorianCalendar instance:
Calendar cal = new GregorianCalendar();
cal.setLenient(false);
References:
GregorianCalendar
setLenient (inherited from Calendar)
Related
If date param is 2015-08-08, in my country (timezone = +7) the day of the month will be 8 – exactly what i want. But in my partner's country (timezone = -8) the day of the month is 7.
Can anyone tell me why?
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
Calendar#getInstance is using the default timezone, which is by default, your own. Any changes that you see are reflected based on your local timezone.
If you want to change that, you can pass in -Duser.timezone as a parameter to your program to ensure that it starts in a specific timezone.
I'm making a little game. When the game is starting for the first time i saves the time since 01.01.1970 in seconds in the SharedPreferences.
Now i want to give this date out on my screen in this form: DD.MM.YYYYY
I used the Calendar function but it give back 02.04.0113 so, there are missing 1900 Years.
Here is my Code:
private void initBornTXT() {
SharedPreferences pref = getSharedPreferences("LIFE", 0);
long born = pref.getLong("BIRTHDAY", 0);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(0);
c.add(Calendar.SECOND, (int)born);
int year = c.getTime().getYear();
int month = c.getTime().getMonth();
int day = c.getTime().getDay();
String string_born = String.format("%02d.%02d.%04d", day, month, year);
TextView born_txt = (TextView)findViewById(R.id.textViewBorn);
born_txt.setText(string_born);
}
What coud be wrong?
Nothing's wrong. You've just not looked at the documentation for the method you're calling, 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.
Note that you should have received a warning that you're using a deprecated API: don't just ignore those warnings.
Also, do yourself a favour and don't do the formatting yourself: use SimpleDateFormat instead. (Or ideally, use Joda Time instead...) That way you can avoid the month being wrong, too... you may not have noticed that you're a month off due to months being 0-based, which is common to both Calendar and Date.
That's normal, documented behavior. See JavaDoc for Date#getYear().
A better way to get the year would be:
c.get(Calendar.YEAR)
You're using getTime, which returns a date object. Dates are based on 0=1900. So this is the expected output. Use a SimpleDateFormat instead.
Kudos for creating a Y2K bug though :)
I have been using java.util for all date and calendar representations. But I am facing a strange problem here. Calendar.MONTH, Calendar.DAY_OF_MONTH, etc all give wrong outputs. But when I use Calendar.getTime(), I get the right output. What might be the problem?
public class TestClass {
public static void main(String[] args) {
Calendar rightNow = Calendar.getInstance();
System.out.println(rightNow.MONTH);
System.out.println(rightNow.DAY_OF_MONTH);
System.out.println(rightNow.YEAR);
System.out.println(rightNow.getTime());
}
}
And the output for the same is:
2
5
1
Tue Jan 22 10:31:44 GMT+05:30 2013
System.out.println(rightNow.MONTH);
System.out.println(rightNow.DAY_OF_MONTH);
System.out.println(rightNow.YEAR);
System.out.println(rightNow.getTime());
You are printing Calendar constant values.
If you want values, you need to do get....
Example:
System.out.println(rightNow.get(Calendar.MONTH));
Read Calendar javadoc for more information.
Calendar.MONTH doesn't return the current month. It is a constant whose value is 2.
From the source:
public final static int MONTH = 2;
It is for use as a parameter in Calendar's get method
public int get(int field) {...}
The design of Calendar is from the early days of Java, when many of today's conventions were different, non-existant, or developing. Oracle (and earlier, Sun), would never let an API like the java.util.Calendar API become part of the standard API today.
And, for completeness, use Joda Time instead of Java's Date and Calendar API's.
java.time
ZonedDateTime rightNow = ZonedDateTime.now(ZoneId.of("Africa/Cairo"));
System.out.println(rightNow.getMonth());
System.out.println(rightNow.getMonthValue());
System.out.println(rightNow.getDayOfMonth());
System.out.println(rightNow.getYear());
System.out.println(rightNow);
Output when running just now was:
FEBRUARY
2
15
2019
2019-02-15T21:15:06.313809+02:00[Africa/Cairo]
Don’t use Calendar
The Calendar class is confusing and suffers from poor design, so no wonder that you’re wondering. Fortunately it was replaced the year after you asked this quesion by ZonedDateTime and other classes in java.time, the modern Java date and time API. So never use Calendar again now.
The Calendar class was trying to be very general, so instead of a getMonth method, etc., it had the notion of fields that could be read and set. Since it was designed long before Java had enums, each field had a number and a named constant for that number. So YEAR (of era) was 1, MONTH was 2, etc. To get the value of the field of a Calendar object you were supposed to call the get method passing the appropriate named constant, for example rightNow.get(Calendar.MONTH). Using just rightNow.MONTH is a regularly repeated mistake. It just gives you the value of the constant, 2.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Calendar now = Calendar.getInstance();
out.println("month now= " + (now.get(Calendar.MONTH)+1));
OR with GregorianCalender:
GregorianCalendar nu = new GregorianCalendar();
int day = nu.get(Calendar.DAY_OF_MONTH);
int month = (nu.get(Calendar.MONTH)+1); //month +1 because january`==0
int year= nu.get(Calendar.YEAR);
int hour= nu.get(Calendar.HOUR_OF_DAY);
int minutes= nu.get(Calendar.MINUTE);
here
I have 2 questions:
How can I find what is the day of the week according to a specific date in JAVA ?
I want to find a difference between 2 times (each time include date and hour) in Java or PHP, someone can help me with that?
Thanx,
EDIT:
I still have a problem with that, I dont success to find the date of a specific date... i'm trying 2 ways, boths are not working.
1.
GregorianCalendar g = new GregorianCalendar(year, month, day, hour, min);
int dayOfWeek=g.DAY_OF_WEEK;
2.
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, hour, min);
int dayOfWeek2 = cal.get(Calendar.DAY_OF_WEEK);
Someone cane give me another solution?
While not particularly great, the standard Java Calendar class should be sufficient for solving your first problem. You can set the time of a Calendar instance using a Date object, then access the DAY_OF_WEEK field. Something like this:
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
As for the second problem, it depends how you want the difference to be measured. If you just want the difference in milliseconds, you can simply call the getTime() method on each of your Date instances, and subtract one from the other. If you want it in terms of seconds, minutes, hours, days, etc you can simply do some simple arithmetic using that value.
Refer these links,
Find day of the week
to find the day of the week according to a specific date
try like below,
Calendar calendar=Calendar.getInstance();
calendar.setTime(specific_date);
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
Find the difference between two times
I'm attempting something and I'm not quite sure how to approach it. I have two user defined values.....a duration and a duration unit. At this point I will already have a start date, so I want to apply the duration and durationUnit somehow to startDate to get the endDate.
Duration is a decimal, durationUnit a HardCode/AbstractCode value and startDate is a Date.
So if the startDate is 17/12/2010......and the user enters the following;
Duration: 3
Duration Unit: Months
I want the endDate to then be calculated as 17/03/2011. Any idea on how I could do this? The duration unit could be Days, Months or Years.
Thanks in advance!
Have a look at joda-time. It's a superb replacement for Date/Calendar. You can do things like:
DateTime newDate = startDate.plusDays(days);
.plusYears(years);
Period toAdd = periodFormatter.parse(inputString);
DateTime newDate = startDate.plus(toAdd);
You can map the Day/Month/Year to the appropriate Calendar DAY, MONTH or YEAR. Then use calendar.add().
If by decimal you mean a double then you will probably have to do some processing to turn parts of a value into appropriate values (such as changing .5 DAY to 12 hours).
DateFormatter is also of use if you want a date to be represented in different styles.
Here, for the sake of brevity, the methods are invoked on classes which you should instatiate first whether using a factory or a constructor. The following statements are only for grasping the idea. Consult JavaDoc API for further details.
Calendar.set(...) //(to set year, month and day).
Calendar.add(...)//(to add a value on specific unit (month, day or year))
Calendar.getInstance() //(return Date object)
DateFormat.format(..) //(return a String representing a style used at instantiation of //DateFormat)
Haven't you tried using the Date type
Date myDate = new Date();
myDate.setMonth();
myDate.setDay();
I haven't use it myself, so i can really, tell you i f it really works, but you shoul give it a try
Others said it already, here a more concrete sample using java.util.Calendar:
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
if(durationUnit.equals("day")){
cal.add(Calendar.DATE, duration);
} else if(durationUnit.equals("month")){
cal.add(Calendar.MONTH, duration);
} else if(durationUnit.equals("year")){
cal.add(Calendar.YEAR, duration);
}
Date endDate = cal.getTime();