3

I have been trying to use the date.format(DateTimeFormatter formatter) method to format a list of date strings, where 'date' is a java.time.LocalDate object, for example. The problem is, I cannot find a straight-forward way to create a Year object from a string. For instance, if I have the string yearString = "90". I would like to create a Year object that is equal to this value, and then use the format method to output yearStringNew = "1990". The closest I see to a public constructor is the now() function which returns the current time.

I have also looked into creating a Calendar object and then creating a format-able date object there, but I can only create a Java.util.Date object – as opposed to an object in the Java.time package which could then ideally be formatted by the format function. Am I missing something here?

FYI I'm referencing the Java 8 SDK javadoc https://docs.oracle.com/javase/8/docs/api/

Thank you for your time.

EDIT: Per the request of another user, I have posted my code below; this is the closest I have come to accomplishing what I'm looking for:

//Module 3: 
//Format Date Segments

package challenge245E;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class TestClass3 {

    public static void main(String[] args) throws ParseException {

        DateFormatter dateFormatter = new DateFormatter();

        String myGroupedSlices [][] = 

            {
                {"1990", "12", "06"},
                {"12","6", "90"}
            };

        dateFormatter.formatDates(myGroupedSlices);

        } 

    }

class DateFormatter {

    public Date[][] formatDates(String[][] groupedDates) throws ParseException {

        Date[][] formattedDates = new Date[groupedDates.length][3];

        DateFormat yearFormat = new SimpleDateFormat("YYYY");
        DateFormat monthFormat = new SimpleDateFormat("MM");
        DateFormat dayFormat = new SimpleDateFormat("dd");

        //iterate through each groupedSlices array
        for (int i=0; i<groupedDates.length;i++) {

            //Conditions

            if (groupedDates[i][0].length()<3) {
                //MDDYY format: if date[0].length < 3

                //Re-arrange into YDM order
                String m = groupedDates[i][0];
                String y = groupedDates[i][2];     
                groupedDates[i][0] = y;
                groupedDates[i][2] = m;

                //convert dates to correct format
                formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
                formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
                formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);

                //testing if block
                System.out.println("MDY Order: " + Arrays.toString(formattedDates[i]));

            }

            if (groupedDates[i][0].length()>3) {
                //YYYYMMDD format: if date[0].length > 3

                //convert dates to correct format
                formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
                formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
                formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);

                //testing if block
                System.out.println("YMD Order: " + Arrays.toString(formattedDates[i]));
            }


        }

        return formattedDates;
    }
}
BenWS
  • 521
  • 2
  • 6
  • 20
  • see [joda-time-how-to-parse-a-string-to-joda-localdate](http://codetutr.com/2013/03/05/joda-time-how-to-parse-a-string-to-joda-localdate/) – mehere Feb 07 '16 at 18:17
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 12 '19 at 23:14

4 Answers4

4

If I understand your requirement correctly, have a look at the LocalDate.parse() methods.

Example:

LocalDate date = LocalDate.parse("1990-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
int year = date.getYear(); // 1990
NilsH
  • 13,705
  • 4
  • 41
  • 59
  • Thanks for this answer – I was running into some issues with the ofPattern method for formatting a year date ("90" as opposed to "90-01-12" for example), but I have found a way around this. I'll have to look at the class methods more closely next time. Thanks again! Would upvote if had had the privilege. – BenWS Feb 08 '16 at 14:28
1

Parse Each Number Separately

It’s good to see you using the java.time framework rather than the troublesome old date-time classes. The old java.util.Date/.Calendar classes have been supplanted by the new framework.

The DateTimeFormatter class parses any two digit year as being in the 2000s. From class doc:

If the count of letters is two… will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.

To override this behavior, see this Answer by assylias. But that issue may be moot in your case. You already have the individual year, month, and date values isolated. So they need not be parsed together.

I suggest you convert each string into a integer. For the year, if less than 100 then add 1900.

String inputYear = "90";
String inputMonth = "12";
String inputDayOfMonth = "6";

int year = Integer.parseInt( inputYear );
int month = Integer.parseInt( inputMonth );
int dayOfMonth = Integer.parseInt( inputDayOfMonth );

if( year < 100 ) { // If two-digit year, assume the 1900s century. Even better: Never generate two-digit year text!
    year = ( year + 1900 );
}

LocalDate localDate = LocalDate.of( year , month , dayOfMonth );
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • I was running into the 2000 to 2099 inclusive issue in trying to parse this specific date earlier – it's helpful to at least know now there's not a built-in way to get around this. As for the two-digit year – the specific scenario involves formatting a variety of dates, some of which might have the two-digit year – anyways I created a similar 'if' branch to the one you have written above for such a case. Thanks for your answer, this was very helpful. Would upvote if I had the privilege. – BenWS Feb 08 '16 at 14:24
  • @BenWS There *is* a built-in way to get around this. See [this Answer](http://stackoverflow.com/a/32505814/642706) I linked. Use a `DateTimeFormatterBuilder` and call `appendValueReduced`. – Basil Bourque Feb 08 '16 at 16:17
0

Create an Instance of class GregorianCalendar, set your date in that calendar and then use the method toZonedDateTime(). This will give you ZonedDateTime instance. form it you can use method LocalDate.from(TemporalAccessor temporal) method to get your LocalDate. Here how it might look:

//....
GregorianCalendar calendar = new GregorianCalendar();
// Set the deasired date in your calendar
LocalDate localDate = LocalDate.from(calendar.toZonedDateTime());
//...
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
0

import java.time.LocalDate;

public class DaysTilNextMonth {

   public static void main(String[] args) {

          //create an object for LocalDate class

          LocalDate date = LocalDate.now();

          //get today's day

          int today = date.getDayOfMonth();

          //get number of days in the current month

          int numOfDaysInMonth = date.lengthOfMonth();

          //compute the days left for next month

          int dayForNextMonth = numOfDaysInMonth - today;



          //display the result

          System.out.println("The next month is: " + date.plusMonths(7).getMonth());

          System.out.println("We have " + dayForNextMonth + " days left until first day of next month.");

   }

}