BenWS
BenWS

Reputation: 531

Possible to create a Java.time.LocalDate object from a String?

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

Upvotes: 4

Views: 5823

Answers (4)

Kevin Fabre
Kevin Fabre

Reputation: 1

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

   }

}

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 339855

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

Upvotes: 1

Michael Gantman
Michael Gantman

Reputation: 7808

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());
//...

Upvotes: 0

NilsH
NilsH

Reputation: 13821

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

Upvotes: 4

Related Questions