Java 数据清洗
Dennis Lee
Software Engineer
| 产品名称 | 收货日期 |
|---|---|
| 青椒 | 3/1/25 |
| 植物油 | 04-01-2025 |
| 奶酪 | 2025.06.01 |
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
// 指定期望的日期格式 (M/d/yy) DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");// 将字符串转换为 LocalDate LocalDate date = LocalDate.parse("3/1/25", formatter); System.out.println("Date converted from string: " + date);
Date converted from string: 2025-03-01
String[] dates = {"3/1/25", "04-01-2025", "2025.06.01"}; // 输入日期格式 DateTimeFormatter[] formatters = { // 输入中期望的日期格式 DateTimeFormatter.ofPattern("M/d/yy"), // 月/日不补零 DateTimeFormatter.ofPattern("MM-dd-yyyy"), // 月/日补零 DateTimeFormatter.ofPattern("yyyy.MM.dd") };System.out.println("Standardized dates:"); for (int i = 0; i < dates.length; i++) { LocalDate date = LocalDate.parse(dates[i], formatters[i]); // 转为日期 System.out.println("Format " + dates[i] + " as " + date1); }
Standardized dates:
Format 3/1/25 as 2025-03-01
Format 04-01-2025 as 2025-04-01
Format 2025.06.01 as 2025-06-01
// 示例输入日期 LocalDate date = LocalDate.parse("2025-03-01"); // 需要显示为 March 1, 2025 DateTimeFormatter displayFormat = DateTimeFormatter.ofPattern("MMMM d, yyyy");// 按所需格式显示 String formattedDate = date.format(displayFormat); System.out.println("Formatted date: " + formattedDate);
Formatted date: March 1, 2025
import java.time.ZoneId;
LocalDate date = LocalDate.parse("2025-03-01"); // 示例输入日期ZonedDateTime nyTime = date.atStartOfDay(ZoneId.of("America/New_York")); // 将同一时刻转换为洛杉矶时间 ZonedDateTime laTime = nyTime.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));System.out.println("New York time: " + nyTime); System.out.println("Los Angeles time: " + laTime);
New York time: 2025-03-01T00:00-05:00[America/New_York]
Los Angeles time: 2025-02-28T21:00-08:00[America/Los_Angeles]
// 错误:用字符串操作提取月份 System.out.println("Does 3/1/25 start with 3? " + "3/1/25".startsWith("3")); System.out.println("Does 03-15-25 start with 3? " + "03-15-25".startsWith("3"));// 正确:使用标准化日期 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-d-yy"); LocalDate date = LocalDate.parse("03-15-25", formatter); // 转为日期 System.out.println("Month and year of 03-15-25: " + date.getMonth() + " " + date.getYear()); // 获取月/年
Does 3/1/25 start with 3? true Does 03-15-25 start with 3? falseMonth and year of 03-15-25: MARCH 2025
关键导入
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.ZoneId;
DateTimeFormatter.ofPattern()LocalDate.parse()ZoneId.of()、.withZoneSameInstant().format()LocalDate.parse() 解析日期,避免用字符串方法(如 .startsWith())Java 数据清洗