Datetimeformat处理多个输入Java



需要一些建议来解决我的问题。我有两种格式的日期输入方式(input1和input2)。

String input1="12-1-2012 T 10:23:34";
String input2="20-10-2012 T 10:34:22";
String format = "dd-MM-yyyy T HH:mm:ss";
SimpleDateFormat sdf= new SimpleDateFormat(format);

如何使用sdf对象处理input1和input2以产生dd-MM-yyyy T HH:mm:ss

java.time

java.utilDate-Time API及其格式化APISimpleDateFormat过时且容易出错。建议完全停止使用它们并切换到现代Date-Time API。

需要两个DateTimeFormatter实例

您需要两个DateTimeFormatter实例:

  1. 解析:DateTimeFormatter.ofPattern("d-M-uuuu 'T' HH:mm:ss")。请注意,单个M可以解析1-12范围内的月份,单个d可以解析1-31范围内的一天。
  2. 另一个用于格式化:DateTimeFormatter.ofPattern("dd-MM-uuuu 'T' HH:mm:ss").

演示:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("d-M-uuuu 'T' HH:mm:ss", Locale.ENGLISH);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu 'T' HH:mm:ss", Locale.ENGLISH);
String[] arr = { "12-1-2012 T 10:23:34", "20-10-2012 T 10:34:22" };
for (String s : arr) {
LocalDateTime ldt = LocalDateTime.parse(s, parser);
String output = ldt.format(formatter);
System.out.println(output);
}
}
}

:

12-01-2012 T 10:23:34
20-10-2012 T 10:34:22
<<p>

在线演示/kbd>在这里,你可以使用y而不是u,但我更喜欢u而不是y

Trail: Date Time了解更多关于现代Date-Time API的信息.

你得调整一下你的样式:

  • 使用一年中单个数字的月份(甚至可能是月份中的几天,一天中的小时,小时中的分钟和分钟中的秒)
  • 用单引号将T转义

您可以使用现代的方法(从Java 8开始)或过时的方法(不推荐)。

下面是两个例子,每种方式一个:

现代方式(java.time)

public static void main(String[] args) {
String input1 = "12-1-2012 T 10:23:34";
String input2 = "12-01-2012 T 10:23:34";
// define your pattern)
String format = "d-M-uuuu 'T' H:m:s";
// define a DateTimeFormatter from the pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);

// parse both of the Strings using the defined formatter
LocalDateTime ldt1 = LocalDateTime.parse(input1, dtf);
LocalDateTime ldt2 = LocalDateTime.parse(input2, dtf);
// print a result
System.out.println(ldt1 + " and " + ldt2 + " are " 
+ (ldt1.equals(ldt2) ? "equal" : "not equal"));
}

输出
2012-01-12T10:23:34 and 2012-01-12T10:23:34 are equal

过时方式(java.utiljava.text)

public static void main(String[] args) throws ParseException {
String input1 = "12-1-2012 T 10:23:34";
String input2 = "12-01-2012 T 10:23:34";
// define your pattern
String format = "d-M-yyyy 'T' H:m:s";
try {
// create a SimpleDateFormat from the pattern
SimpleDateFormat sdf = new SimpleDateFormat(format);
// parse both of the Strings using the date format
Date date1 = sdf.parse(input1);
Date date2 = sdf.parse(input2);
System.out.println(date1 + " and " + date2 + " are " 
+ (date1.equals(date2) ? "equal" : "not equal"));
} catch (ParseException e) {
e.printStackTrace();
throw(e);
}
}

输出
Thu Jan 12 10:23:34 CET 2012 and Thu Jan 12 10:23:34 CET 2012 are equal

请注意,过时的方式神奇地添加了一个时区,这是CET,因为这段代码在我的德国机器上执行…
对于具有区域或偏移量的日期时间,您将不得不在java.time中使用不同的类,例如ZonedDateTimeOffsetDateTime

MM是两位数字的月份格式,使用值01 - 12。您可能需要使用个位数格式M,它使用值1 - 12。

最新更新