Alex Cauthen
Alex Cauthen

Reputation: 517

Android: Get year, month, day from GregorianCalendar Object

The GregorianCalendar constructor asks for the following:

GregorianCalendar(int year, int month, int dayOfMonth);

How can I extract the year, month, and day from an object I have created. Right now I'm using object.YEAR, object.MONTH, and object.DAY_OF_MONTH, but that does not seem to be giving me the right numbers.

Thanks.

Here I get a date based on which calendar date a user clicks. The user can then enter some information into that date which is stored in a HashMap keyed on GregorianCalendar.

cal.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {

                selectedDate = new GregorianCalendar(year, month, dayOfMonth);

Here I am trying to write the date from the GregorianCalendar year, month, and day parameters to a file to be used later.

private void writeToFile() {
        try
        {
            PrintWriter writer = new PrintWriter(file, "UTF-8");
            for (GregorianCalendar gregObject: recipes.keySet()) {
                String[] value = recipes.get(gregObject);
                int y = gregObject.YEAR;
                int m = gregObject.MONTH;
                int d = gregObject.DAY_OF_MONTH;

                writer.printf("%d %d %d ", y, m, d);

Here is how I read from the file. When I read from the file I get the numbers 1,2,5 for year, month, and date which is wrong. The rest of the information read is correct.

try
            {
                Scanner getLine = new Scanner(file);
                Scanner tokenizer;

                while (getLine.hasNextLine()) {
                    String line = getLine.nextLine();
                    tokenizer = new Scanner(line);
                    System.out.println(line);

                    while (tokenizer.hasNextInt()) {
                        int y1 = tokenizer.nextInt();
                        int m1 = tokenizer.nextInt();
                        int d1 = tokenizer.nextInt();

Obviously I think I am writing the year, month, and day wrongly to the file, so I'm trying to figure out the correct way to extract the year, month, and day from a GregorianCalendar object.

Upvotes: 1

Views: 8095

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338211

tl;dr

  • You are working too hard.
  • You are using troublesome old date-time classes now supplanted by the modern java.time classes.

Example:

LocalDate.now().getYear()      // Better to pass a specific time zone (`ZoneId`) as optional argument: LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).getYear()

2018

java.time

Do not use a date-time class if you really only care about the date without the time.

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.

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( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

year-month-day parts

Interrogate for the parts, as needed.

int ld.getYear() ;
int ld.getMonthValue() ;
int ld.getDayOfMonth() ;

Legacy code

If you must inter-operate with old code not yet converted to java.time, you may convert using new methods added to the old classes.

The equivalent of GregorianCalendar is ZonedDateTime.

ZonedDateTime zdt = myGregCal.toZonedDateTime() ;  // Convert from legacy class to modern class.

Interrogate for the parts, as needed.

int zdt.getYear() ;
int zdt.getMonthValue() ;
int zdt.getDayOfMonth() ;

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.

Where to obtain the java.time classes?

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.

Upvotes: 2

Hari
Hari

Reputation: 141

Hope following helps: I am using 2015/06/10 as input. Please note month values are 0 (Jan) - 11 (Dec).

package demo;

import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * Create on 4/3/16.
 */
public class TestCalendar {

    public static void main(String [] args){
        Calendar cal = new GregorianCalendar(2015,05,10); // Month values are 0(Jan) - 11 (Dec). So for June it is 05
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);      // 0 - 11 
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        // Following must output 2015/06/10
        System.out.printf("Provided date is %4d/%02d/%02d", year, month+1,     dayOfMonth);
    }
}

Upvotes: 3

Related Questions