简体   繁体   English

可以从字符串创建Java.time.LocalDate对象吗?

[英]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. 我一直在尝试使用date.format(DateTimeFormatter formatter)方法来格式化日期字符串列表,例如,“ date”是java.time.LocalDate对象。 The problem is, I cannot find a straight-forward way to create a Year object from a string. 问题是,我找不到从字符串创建Year对象的简单方法。 For instance, if I have the string yearString = "90". 例如,如果我有字符串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". 我想创建一个等于该值的Year对象,然后使用format方法输出yearStringNew =“ 1990”。 The closest I see to a public constructor is the now() function which returns the current time. 我看到的最接近公共构造函数的是now()函数,该函数返回当前时间。

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. 我还研究了创建Calendar对象,然后在其中创建可格式化的日期对象,但是我只能创建Java.util.Date对象,而不是可以理想地格式化的Java.time包中的对象。通过格式功能。 Am I missing something here? 我在这里想念什么吗?

FYI I'm referencing the Java 8 SDK javadoc https://docs.oracle.com/javase/8/docs/api/ 仅供参考,我引用的是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;
    }
}

If I understand your requirement correctly, have a look at the LocalDate.parse() methods. 如果我正确理解了您的要求,请查看LocalDate.parse()方法。

Example: 例:

LocalDate date = LocalDate.parse("1990-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
int year = date.getYear(); // 1990

Parse Each Number Separately 分别解析每个数字

It's good to see you using the java.time framework rather than the troublesome old date-time classes. 很高兴看到您使用java.time框架,而不是麻烦的旧日期时间类。 The old java.util.Date/.Calendar classes have been supplanted by the new framework. 新的框架已取代了旧的java.util.Date/.Calendar类。

The DateTimeFormatter class parses any two digit year as being in the 2000s. DateTimeFormatter类将任何两位数字的年份解析为2000年代。 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. 如果字母数为2…,则将使用2000的基值进行解析,从而得出2000到2099(含)之间的年份。

To override this behavior, see this Answer by assylias . 要覆盖此行为,请参阅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. 对于一年,如果少于100,则加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 );

Create an Instance of class GregorianCalendar, set your date in that calendar and then use the method toZonedDateTime(). 创建类GregorianCalendar的实例,在该日历中设置日期,然后使用方法toZonedDateTime()。 This will give you ZonedDateTime instance. 这将为您提供ZonedDateTime实例。 form it you can use method LocalDate.from(TemporalAccessor temporal) method to get your LocalDate. 从中可以使用LocalDate.from(TemporalAccessortemporal)方法获取LocalDate。 Here how it might look: 这里看起来可能是这样:

//....
GregorianCalendar calendar = new GregorianCalendar();
// Set the deasired date in your calendar
LocalDate localDate = LocalDate.from(calendar.toZonedDateTime());
//...

import java.time.LocalDate; 导入java.time.LocalDate;

public class DaysTilNextMonth { 公共课程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.");

   }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ofInstant 不是对象 java.time.LocalDate 的成员 - ofInstant is not a member of object java.time.LocalDate 将字符串转换为 java.time.localDate - Convert String to java.time.localDate 如何使用“d”从日期字符串创建java.time.LocalDate。 LLLL YYYY“模式? - How do I create a java.time.LocalDate from a date string using the “d. LLLL YYYY” pattern? 要转换的源必须是java.lang.String的实例; 相反,它是一个java.time.LocalDate - source to convert from must be an instance of java.lang.String; instead it was a java.time.LocalDate 无法从 String 值实例化 [简单类型,类 java.time.LocalDate] 类型的值 - Can not instantiate value of type [simple type, class java.time.LocalDate] from String value setCellValue(String value) throws java: cannot access java.time.LocalDate class file for java.time.LocalDate not found - setCellValue(String value) throws java: cannot access java.time.LocalDate class file for java.time.LocalDate not found 数据类型为 java.time.LocalDate 的 @ApiModelProperty 无法解析 - @ApiModelProperty with dataType java.time.LocalDate not resolvable 上周是java.time.LocalDate吗? - Was a java.time.LocalDate in last week? Slick 3 java.time.LocalDate映射 - Slick 3 java.time.LocalDate mapping 导入java.time.LocalDate失败 - Import failing for java.time.LocalDate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM