Java - 取两个字符串并组合成一个日期对象

Cer*_*ner -1 java dateformatter

我正在尝试将两个字符串放入一个 Date 对象中。我在尝试确定我需要使用的格式时遇到了麻烦。

第一个字符串是日期,格式为:5th Jan

第二个字符串是时间,格式为:8:15

主要问题是第 5 次的格式是什么

Arv*_*ash 11

由于您的日期字符串5th Jan没有年份,因此您必须使用一些默认年份,例如当前年份,您可以从LocalDate.now(). 您可以使用DateTimeFormatterBuilder#parseDefaulting. 此外,您还可以使用 使解析器不区分大小写DateTimeFormatterBuilder#parseCaseInsensitive

为了解析日期字符串5th Jan,您可以使用模式d'th' MMM。但是,为了处理 3rd、1st 等其他后缀,您应该使用模式,d['th']['st']['rd']['nd'] MMM其中方括号内的模式是可选的。

为了解析像 那样的时间字符串8:15,您可以使用模式H:m.

演示:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        DateTimeFormatter dtfForDate = new DateTimeFormatterBuilder()
                                        .parseCaseInsensitive()
                                        .parseDefaulting(ChronoField.YEAR, date.getYear())
                                        .appendPattern("d['th']['st']['rd']['nd'] MMM")
                                        .toFormatter(Locale.ENGLISH);

        DateTimeFormatter dtfForTime = DateTimeFormatter.ofPattern("H:m", Locale.ENGLISH);

        String strDate = "5th Jan";
        String strTime = "8:15";

        LocalDateTime ldt = LocalDate.parse(strDate, dtfForDate)
                                        .atTime(LocalTime.parse(strTime, dtfForTime));

        // Print the default string value i.e. the value returned by ldt.toString()
        System.out.println(ldt);

        // The default format omits seconds and fraction of second if they are 0. In
        // order to retain them in the output string, you can use DateTimeFormatter
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
        String formatted = dtf.format(ldt);
        System.out.println(formatted);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

2021-01-05T08:15
2021-01-05T08:15:00
Run Code Online (Sandbox Code Playgroud)

Trail: Date Time了解现代日期时间 API 。