0

So, this program takes user input as a string in the format "m/d/yyyy" or "mm/dd/yyyy." It then display the month as a word (e.g., month 1 becomes "January"). The last thing I need to do is use the GregorianCalendar class to determine the date's ordinal position in the year. I don't really know how to do this. Any help would be greatly appreciated.

import javax.swing.*;
import java.text.*;
import java.util.*;

public class ConvertDate {

   public static void main(String[] args) {


      String date = "";
      String[] monthName = 
         {"January", "February", "March", "April", 
            "May", "June", "July", "August", 
            "September", "October", "November", "December"};

      Integer[] daysInMonth = {29, 30, 31};

      int mm = 0;
      int dd = 0;
      int yy = 0;   

      String month = "";
      String day = "";
      String year = "";

      int maxDay = 0;


      while(mm < 1 || mm > 12 || dd < 1 || dd > maxDay) {            


         date = JOptionPane.showInputDialog(null, "Please, enter a date in the format MM/DD/YYYY.");

         String[] partsOfTheDate = date.split("/");

         mm = Integer.parseInt(partsOfTheDate[0]); 
         dd = Integer.parseInt(partsOfTheDate[1]);
         yy = Integer.parseInt(partsOfTheDate[2]);

         switch (mm) {
            case 1:  maxDay = daysInMonth[2]; // Jan
               break;
            case 2:  maxDay = daysInMonth[0]; // Feb 
               break;
            case 3:  maxDay = daysInMonth[2]; // Mar
               break;
            case 4:  maxDay = daysInMonth[1]; // Apr
               break;
            case 5:  maxDay = daysInMonth[2]; // May
               break;
            case 6:  maxDay = daysInMonth[1]; // Jun
               break;
            case 7:  maxDay = daysInMonth[2]; // Jul
               break;
            case 8:  maxDay = daysInMonth[2]; // Aug
               break;
            case 9:  maxDay = daysInMonth[1]; // Sep
               break;
            case 10: maxDay = daysInMonth[2]; // Oct
               break;
            case 11: maxDay = daysInMonth[1]; // Nov
               break;
            case 12: maxDay = daysInMonth[2]; // Dec
               break;
            default: maxDay = 0;
               break;
         }

         if((mm < 1 || mm > 12) || (dd < 1 || dd > maxDay)) {
            System.out.println("You entered " + date + ";\nyou did not include a valid month, day, or both.");
         }   
         else if((mm > 0 && mm < 13) && (dd > 0 && dd <= maxDay)) {
            System.out.println("You entered " + date + ";\nthat can also be expressed as " + monthName[mm - 1] + " " + dd + ", " + yy + ".");   
         }     

         GregorianCalendar greg = new GregorianCalendar();  
         greg.setTime(date);  
         greg.get(greg.DAY_OF_YEAR); 

      }   

   }  

}
user2817128
  • 21
  • 1
  • 2
  • 5

4 Answers4

5

Use SimpleDateFormat to parse String to Date and then set Date to Calendar and get the day_of_year


Related

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 3
    +1. And do the same to get the month, instead of reinventing the wheel. – JB Nizet Nov 02 '13 at 23:53
  • Thank you very much for the feedback, Jigar. JB, I _have_ to use GregorianCalendar as this is for an assignment. The assignment also calls for the date to be inputted in the above manner. – user2817128 Nov 03 '13 at 00:25
0

Use Calendar greg = new GregorianCalendar(); greg.setTime(date_format);

You can convert the user input string to date_format by using java 'Date' class.

Check resource here... http://pic.dhe.ibm.com/infocenter/adiehelp/v5r1m1/index.jsp?topic=%2Fcom.sun.api.doc%2Fjava%2Futil%2FGregorianCalendar.html

  • Thank you for your response, Soumya. I've looked at that GregorianCalendar info at the link you provided at least a thousand times over the past week and don't feel any closer to understanding the information. I have no idea how to use the "Date" class. – user2817128 Nov 03 '13 at 00:33
  • This resource might be useful to you. http://www.mkyong.com/java/how-to-convert-string-to-date-java/ –  Nov 03 '13 at 00:47
0

You also don't have to use all of those cases

you can just do it like

case 6:
case 2:
case 3:
aMethod();
break;
case 4:
anotherMethod();
break;

This works because when it happens to be case 1 (for instance), it falls through to case 2 (no break statement), which then falls through to case 3.** Look here Avoid Switch statement redundancy when multiple Cases do the same thing?

makes for less code that's is easier to read anyway.

Kumar pretty much got the rest for you

Community
  • 1
  • 1
Kevin Johnson
  • 218
  • 1
  • 3
  • 10
0

tl;dr

LocalDate.parse(                                 // Produce a `java.time.LocalDate` object, a date-only value without time-of-day and without time zone.
    "mm/dd/yyyy" , 
    DateTimeFormatter.ofPattern( "MM/dd/uuuu" )  // Specify formatting pattern to match your input string.
)
.getMonth()                                      // Get the `Month` 
.getDisplayName( FormatStyle.FULL , Locale.US )  // Translate the name of month to the human language and cultural norms of a particular `Locale`.

January

And…

LocalDate.parse(   
    "mm/dd/yyyy" , 
    DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) 
)
.getDayOfYear()                                   // Ordinal day number, 1-365 or 1-366 in a Leap Year.

324

java.time

You are using troublesome old date-time classes that are now obsolete legacy, supplanted by the java.time classes.

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 ) ;

For the month name, use the Month enum objects.

Month m = ld.getMonth() ;

Generate a localized string for the name of the month.

String output = m.getDisplayName( TextStyle.FULL , Locale.US ) ; // Or Locale.CANADA_FRENCH and so on.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section left intact for history.

The 3rd-party library, Joda-Time, makes much easier work of your question.

Name of Month

Read the Quick start guide around the 5th paragraph. A DateTime object has properties and fields from which information may be gleaned, such as the name of a month.

Day of Year

Joda-Time provides a Property appropriately named dayOfYear.

Example Code

Using Joda-Time 2.3 on Java 7 on OS X Mountain Lion in IntelliJ 13.

org.joda.time.DateTime now = new org.joda.time.DateTime();
System.out.println("Now: " + now );

String monthName = now.monthOfYear().getAsText();
System.out.println("Name of Month: " + monthName );

String dayOfYear = now.dayOfYear().getAsString();
System.out.println("Day of Year: " + dayOfYear );

When run:

Now: 2013-11-03T01:39:38.278-07:00
Name of Month: November
Day of Year: 307

Notes about Joda-Time and this example code:

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/

// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310

// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601

Parsing a string input by a user, to create a DateTime object is a whole other subject and should be a separate question. I ignored that aspect of your question, and instead focused on your title: Day of Year.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154